How are constants defined in the C language?
In C language, constants can be defined using the #define or const keyword.
- Define using macros:
- This code calculates the area of a circle with a radius of 5 using the value of PI, which is defined as 3.14159.
- In the above code, #define is used to define the constant PI. In the subsequent code, PI can be directly used to represent 3.14159. It is important to note that #define does not define a variable, but rather replaces PI with 3.14159 wherever it appears in the code.
- Define constants using the const keyword.
- #include
int main() {
const float PI = 3.14159;
float radius = 5;
float area = PI * radius * radius;
printf(“The circle’s area is: %f\n”, area);
return 0;
} - In the code above, a floating point constant PI is defined using the const keyword, and is then used in the subsequent code. Constants defined with the const keyword have a data type and cannot be changed.
The two ways of defining constants are functionally equivalent, and the choice between them depends on personal preference and coding style.