Prerequisite – Constants in C
Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types.
Types of Constant in C :
C supports several types of constants in C language as
- Character Constants, i.e., Single Character Constant, and String Constant.
- Numeric Constants :
- Integer Constant, i.e., Decimal Integer constant, Octal integer constant, and Hexadecimal Integer constant.
- Real Constant
- Backslash Character constants
- Symbolic constants
Defining Constants :
There are two simple ways in C to define constants − Using #define preprocessor, and Using const keyword.
- Using #define preprocessor directive –
Given below is the form to use #define preprocessor to define a constant −#define identifierName value
- identifierName : It is the name given to constant.
- value : This refers to any value assigned to identifierName.
Example :
#include <stdio.h> #define LENGTH 100 #define WIDTH 50 #define NEWLINE '\n' int main() { int area; //test these values printf("Value of LENGTH is %d", LENGTH); printf("%c", NEWLINE); printf("Value of WIDTH is %d", WIDTH); printf("%c", NEWLINE); //check using calculation area = LENGTH * WIDTH; printf("Value of area is %d", area); return 0; }
Output :
Value of LENGTH is 100 Value of WIDTH is 50 Value of area is 5000
- Using const Keyword :
You can use const prefix to declare constants with a specific type as follows −const type variable = value;
Example :
#include <stdio.h> int main() { const int LENGTH = 100; const int WIDTH = 50; const char NEWLINE = '\n'; //test these values printf("Value of LENGTH is %d", LENGTH); printf("%c", NEWLINE); printf("Value of WIDTH is %d", WIDTH); printf("%c", NEWLINE); //check using calculation int area; area = LENGTH * WIDTH; printf("value of area is %d", area); printf("%c", NEWLINE); return 0; }
Output :
Value of LENGTH is 100 Value of WIDTH is 50 value of area is 5000
Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.