The keyword const can be added to the declaration of an object to make that object a constant rather than variable. |
|
The general form of constant declaration is as follows: |
|
Syntax: const int a=50; |
|
Constants can be classified based on their data type. |
|
The various types are- |
|
Numeric type constants |
character constants |
String |
|
Numeric type constants |
|
Numeric constants consist of a series of digits. Integer constants can be written in different |
|
number systems: |
hexadecimal (base 16), octal (base 8) or in decimal (base 10). |
|
A decimal integer constant is any normal whole number (can consist of digits from 0 to 9): |
|
2,34, 100, 900, 1456 etc. |
|
An octal integer constant can contain digits from 0 to 7 only and it should start with a zero (so that the computer will know it is an octal number). |
|
For example: |
|
023, 0567, 0214 etc. |
|
A hexadecimal integer constant should start with 0x or 0X and can consist of digits from 0 to 9 and A to F (uppercase and lowercase letters are allowed). |
|
For example: |
|
0x10, 0x1FF etc. |
Floating point constants will have the decimal point in the number. |
|
Character and String Constants |
|
Character constants are single characters enclosed within two single quotes (or between two apostrophes). |
|
For example: |
|
‘a’ , ‘b’ , ‘x’ , ‘1’ , ‘A’ , ‘*’ |
|
A single character enclosed within single quotes is a character constant. All character constants will have an integer value (determined from the ASCII table). A C++ statement: |
|
char ch = ‘B’; |
|
will assign the character constant ‘B’ to the character variable ch. |
|
String constants consist of a series of characters enclosed within double quotes. |
|
For example: |
|
“hello” |
“This is a string” |
“x” |
|
Even “x” is a string because it is enclosed in double quotes. “x” is different from ‘x’ (this is a character constant). The reason is because “x” actually consists of ‘x’ and ‘\0’ (the null character which will be explained later). |
|
Structure |
|
A structure is a collection of data of different data types under one name. e.g. |
|
Struct employees |
|
{ |
char Name[10]; |
int Age; |
int Salary; |
}; |
|
Union |
|
It is a collection of data of different types sharing common memory space. e.g. |
|
Union item |
{ |
int m; |
float x; |
char c; |
}; |
|
Enumerated Data types |
|
This data types gives us an opportunity to invent your own data type and define what values the variable of this data type can take. |
|
Example: |
enum colors |
|
{ |
red, green, blue, cyan |
}; |
|
colors foreground, background; |
|
Here the declaration has two parts: |
|
The first part declare the data type and specifies its possible values. |
The second part declare variable of this data type. |
|
Now we can give the values to these variables: |
foreground=red; |
background=blue; |
|
But remember we can’t use values that aren’t in the original declaration. Thus, the following declaration cause error. |
|
foreground=yellow; |