table of Contents
Define constants:
In C, there are two simple ways to define constants:
- Use #define preprocessor.
- Use the const keyword.
#define preprocessor
The following is the form of using #define preprocessor to define constants:
#define identifier value
For details, please see the following example:
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it will produce the following results:
value of area : 50
const keyword
You can use the const prefix to declare constants of a specific type, as follows:
const type variable = value;
For details, please see the following example:
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it will produce the following results:
value of area : 50
Please note that it is a good programming practice to define constants as capital letters.