Declaring a Constant Variable in C programming

Declaring a Constant Variable in C

Declaring a Constant Variable in C

In C programming, a constant variable is a variable whose value cannot be changed once it has been initialized. To declare a constant variable, you use the const keyword. This is useful for values that are meant to remain the same throughout the execution of the program.

Syntax for Declaring a Constant Variable

const data_type constant_name = value;

Explanation:

  • const: The keyword used to declare a constant variable.
  • data_type: The type of data the constant will hold (e.g., int, float).
  • constant_name: The name of the constant variable. It is common practice to use uppercase letters for constant names.
  • value: The initial value assigned to the constant. This value cannot be changed later in the program.

Example

#include <stdio.h>

int main() {
    // Declaration of constant variables
    const int MAX_VALUE = 100;
    const float PI = 3.14159;

    // Print the constant values
    printf("Max Value: %d\\n", MAX_VALUE);
    printf("Value of PI: %.5f\\n", PI);

    return 0;
}

In this example:

  • MAX_VALUE is a constant integer with a value of 100.
  • PI is a constant floating-point number with a value of 3.14159.
  • Both constants are initialized at the time of declaration and cannot be modified later in the program.
Note:
Use const for values that should not change throughout the program to prevent accidental modification and to make your code more readable and maintainable.

Comments

Popular Posts