A constant is similar to the variable but the constant hold only one value during the program execution.That means, once a value is assigned to the constant, that value can't be changed during the program execution. Once the value is assigned to the constant, it is fixed throughout the program.
In C programming language, a constant can be of any data type like integer, floating-point, character, string and double, etc.
An integer constant can be a decimal integer or
octal integer or hexadecimal integer. A decimal integer value is
specified as direct integer value whereas octal integer value is
prefixed with 'o' and hexadecimal value is prefixed with 'OX'.
An
integer constant can also be unsigned type of integer constant or long
type of integer constant. Unsigned integer constant value is suffixed
with 'u' and long integer constant value is suffixed with 'l' whereas
unsigned long integer constant value is suffixed with 'ul'.
Example
125 -----> Decimal Integer Constant
O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant
A floating-point constant must contain both integer and decimal parts. Some times it may also contain the exponent part. When a floating-point constant is represented in exponent form, the value must be suffixed with 'e' or 'E'.
Example
The floating-point value 3.14 is represented as 3E-14 in exponent form.
A character constant is a symbol enclosed in single quotation. A character constant has a maximum length of one character.
Example
A string constant is a collection of characters,
digits, special symbols and escape sequences that are enclosed in double
quotations.
We define string constant in a single line as follows...
"Hello Everyone"
In a c programming language, constants can be created using two concepts...
- Using the 'const' keyword
- Using '#define' preprocessor
We create a constant of any datatype using
'const' keyword. To create a constant, we prefix the variable
declaration with 'const' keyword.
The general syntax for creating constant using 'const' keyword is as follows...
const datatype constantName ;
or
const datatype constantName = value ;
Example
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5 ;
const int j = 100 ;
i = 50 ;
j = 200 ;
printf("i = %d\nj = %d", i, j ) ;
getch();
}
Output
The above program gives an error because we are trying to change the constant variable value (j = 200).
The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.
We use the following syntax to create constant using '#define' preprocessor directive...
#define CONSTANTNAME value
Example
#include <stdio.h>
#include<conio.h>
#define PI 3.14
main() {
printf("%f",PI);
getch();
}
Output
No comments:
Post a Comment