CPP Language / Variables, Data Types and Constants
Variable
It is a data named used to store a data value.
Syntax of Variable declaring
data_type variable1_name = value1, variable2_name = value2;
Example
int n1=20, n2=100;
Data Types
It is an attribute of data which tells the compiler / interpreter how the programmer intends to use the data.
Data Type
|
Size in Bytes
|
Range
|
short int
|
2
|
-32,768 to 32,767
|
unsigned short int
|
2
|
0 to 65,535
|
unsigned int
|
4
|
0 to 4,294,967,295
|
int
|
4
|
-2,147,483,648 to 2,147,483,647
|
long int
|
4
|
-2,147,483,648 to 2,147,483,647
|
unsigned long int
|
4
|
0 to 4,294,967,295
|
long long int
|
8
|
-(2^63) to (2^63)-1
|
unsigned long long int
|
8
|
0 to 18,446,744,073,709,551,615
|
signed char
|
1
|
-128 to 127
|
unsigned char
|
1
|
0 to 255
|
float
|
4
|
|
double
|
8
|
|
long double
|
12
|
|
wchar_t
|
2 or 4
|
1 wide character
|
Constants
Constants are to fixed values they don’t change during the execution of a program.
Defining Constants are of 2 types
1. Using #define preprocessor. |
#include
using namespace std;
#define LENGTH 10
#define WIDTH 5
int main() {
int area;
area = LENGTH * WIDTH;
cout << area;
return 0;
}
Output:50
|
2. Using const keyword.
const type variable = value;
|
#include
using namespace std;
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
int area;
area = LENGTH * WIDTH;
cout << area;
return 0;
}
Output:50
|
Type of Constants
|
Details
|
Example
|
Integer
|
It can be decimal, octal, or hexadecimal Constant
|
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long
|
Floating point
|
It has an integer part, a decimal point, a fractional part, and an exponent part
and represented in decimal / exponential form. The signed exponent is introduced
by e or E.
|
3.14159, 314159E-5L
|
Boolean
|
It consists of either true / 1 or false / 0
|
either true or false
|
Character
|
It is enclosed in single quotes.
|
'x'
|
String
|
It is enclosed in double quotes.
|
hello Wisdom Materials",
|
|