- Constant variables you declare yourself like variables.
- The advantage of using Constant variables is that if you have to change constant later, then you do not need to change it in many places in the program.
- You just change the value of constant variable and in that program your You change.
- You can declare constant variables in two ways.
- These are being described below.
- User #Define Directive
- Using const Keyword
❖ User #Define Directive :-
- #define is a pre processor directive and you declare constant variables by using it.
- This directive is declared before the main function at the beginning of the constant variables program.
- You can use any of the program's constant variables defined by this directive.
The use of constant variables is being explained by the example below.
# include <stdio.h>
/* Defining constant */
#define result 10
int main()
{
int a=5, b=6;
/* Wrong, (error) Value of constant result variable can not be changed. */
result = a + b;
printf(“%d”, result);
return 0;
}
The above program produces the below given output.
error : lvalue required as left operand of assignment
result = a + b;
❖ Using const Keyword :-
- You can declare constant variables even by const keyword in C language.
- If you want to use constant variable only in a function, you can declare constant variable through this keyword.
The use of const keyword in C language is being explained by the example below.
#include<stdio.h>
int main()
{
const int a=5;
const int b=6;
int c; /* Adding two constants */
c = a+b;
printf(“Result is : %d”,a);
return 0;
}
The above program produces the below given output.
Result is : 11
❖ Types of C Constants :-
- Integer Constants
- Floating-Point Constants
- Character Constants
- String Constants
- Enumeration Constants
Apart from these, the escape sequence characters in C language are also considered
constants.
No comments:
Post a Comment
Please do not any spam link in Comment Box