In this article, we will discuss variables, constants, and literals in C++ programming language with examples.
C++ Variables
In programming, variables are containers for storing data values. It is basically a name given to a memory location and this name must be unique, you cannot use the same variable name for two different memory locations. The value that you will store in a variable can be changed during the execution of the program.
syntax: data_type variable_name; example: int count = 10;
![]() |
Variables in C++ |
- A variable name can contain only alphabets, digits, and underscores.
- A variable name must begin with an alphabet or underscore, it cannot begin with a number.
- A variable name should not contain any whitespace or special characters like #, $, @, %, *, etc.
- A variable name is case-sensitive in nature. Ex: num and Num is two different variables.
- One cannot use C++ reverse keywords (Ex: int, float, for) as a variable name.
Note: It is suggested to start a variable name with lowercase alphabets and try to give always meaningful variable names. (alert-success)
C++ Constant
In C++ programming, constants are those kinds of variables whose values are fixed and cannot be changed. These kinds of variables are defined using the const keyword and they have read-only property. Example:
const float PI = 3.14 PI = 3.141 //Error: value of PI is constant
C++ Literals
- Decimal (base 10): It is the Normal representation of numbers that we use in daily life. Ex: 25
- Octal (base 8): Integer literals that begin with 0 are interpreted as octal. Ex: 031 is an octal representation of 25.
- Hexadecimal (base 16): Integer literals that begin with 0x or 0X are interpreted as hexadecimal. Ex: 0x19 is a hexadecimal representation of 25.
//C++ example of Integer Literals #include<iostream> using namespace std; int main() { int x, y, z; x = 25; y = 031; z = 0x19; cout<<"Decimal Representation: "<<x<<endl; cout<<"Octal Representation: "<<y<<endl; cout<<"Hexadecimal Representation: "<<z<<endl; return 0; }
Decimal Representation: 25
Octal Representation: 25
Hexadecimal Representation: 25
Example: 3.52341 3.52341E2 = 3.52341x10^2 = 352.341 3.52341e2 = 3.52341x10^2 = 352.341 3.52341E-1 = 3.52341x10^-1 = 0.352341
//C++ example of Floating Point Literals #include<iostream> using namespace std; int main() { float x, y, z, n; x = 3.52341; y = 3.52341E2; z = 3.52341e3; n = 3.52341E-1; cout<<x<<endl; cout<<y<<endl; cout<<z<<endl; cout<<n<<endl; return 0; }
3.52341
352.341
3523.41
0.352341
Note: The compiler appends a null character ('\0') to every string literal. Thus, the actual size of a string literal is one more than its apparent size. (alert-success)
No comments:
Post a Comment