In this tutorial, we will learn about variables, literals, and constants in C++ with the help of many examples.
C++ Variables
Here, age is a variable of the int data type, and we have assigned an integer value 20 to it.
age = 10; // age is 10
The value of a variable can be changed, hence the name
variable.
Rules for naming a variable
- A variable name can't be a keyword. For e.g. int can't be a variable name as it is a keyword.
- Variable names can have alphabet (A-Z and a-z), underscore ( _ ), digits (0-9) but can't have other symbols such as %, @ etc. For Example ali_hamza, count are valid variables name but ali@, count% are not allowed.
- Variable name must start with an alphabet (A-Z and a-z) or underscore ( _ ) sign. For e.g. ali, X and _bilal etc are valid variable names but 1ali, $age etc are invalid variable name.
Some valid variable names are: ali_hamza, _age, count, y etc.
Some invalid variable names are: 1user, %marks, bil@l, ali!, *age* etc.
Literals
A literal is a notation for representing a fixed value in
source code. For example: 3, 'bilal' , 2.1 , 'a' etc.
Here, 3,
'bilal' , 2.1 , 'a' are literals. Why? You cannot assign different
values to these terms.
-
Integer :
Integer literals represent different integer values. There are several ways to use integer literals in your code. There are three types of integer literals in C++ programming:
- decimal (base 10)
- octal (base 8)
- hexadecimal (base 16)
For Example:int decimal = 123; // Decimal
int octal = 0175; // Octal
int hexa = 0xa1b; // Hexadecimal
-
Floating Point :
A floating point literal consist of decimal values also having their fractional part.
For Example:float count = 13.2;You can use the floating point integers with the exponent part.
For example:float value1 = 0.001; float value2 = 1.0E-3; -
Character :
A character literal is a single character that is enclosed by single quotes.
For Example:char a = 'H';
char b = 'f';
char c = 'M'; -
String :
String literals are the sequence of the characters that are enclosed by double quotes.
For Example:"This is string literal"
-
Escape Sequences :
There are some special characters that are used for different purposes in character literals.
\n New Line \t Horizental Tab \' Single Quotation Mark \? Question Mark \\ Backslash \a Alert \f Formfeed \r Carriage Return \b Backspace \v Vertical Tab "\ Double Quation Mark \ooo Octal Nmber \xhhh Hexadecimal Nmber \0 Null Chracter
C++ Constants
Constant is something that doesn't change. In C++ we use the keyword const to make program elements constant.
For example:x = 5 ;// Error! x is constant.
0 Comments
if you have any doubt in programming concept please let me know