Tuesday 11 September 2012

C++ ( Tutorials VII )

Constant Mean :-

Constants are used in expressions and their values cannot be changed. They are used in the program code without using any variable name to refer to them. For example consider the statements:
int x = 5;
float y = 3.33;

In this, 5 is an integer constant and 3.33 is a floating type constant. You cannot change 5 or 3.33 but you can assign these values to variables (the variables in the above code fragment are ‘x’ and ‘y’).


Constants can be classified based on their data type as follows:

1.) Numeric type constants (includes integers, floating-point etc.)
2.) Character and String Constants.

1.) Numeric 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.) A decimal integer constant is any normal whole number (can consist of digits from 0 to 9):
2,34, 100, 900, 1456 etc.

b.) 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.

c.) 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.

d.) Floating point constants will have the decimal point in the number.

2.) Character and String Constants:-

 a.) 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.

b.) 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).

c.) Constants are also called as ‘literal’. You might come across the terms character literal, integer literal, string literal etc.

0 comments:

Post a Comment