How are constants defined in the C language?

In C language, constants can be defined using the #define or const keyword.

  1. Define using macros:
  2. This code calculates the area of a circle with a radius of 5 using the value of PI, which is defined as 3.14159.
  3. 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.
  4. Define constants using the const keyword.
  5. #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;
    }

  6. 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.

bannerAds