In C programming language, a constant is a value that cannot be changed during the execution of a program. Constants can be defined using the const keyword, which tells the compiler that the value of the variable cannot be changed.
Constants can be defined using any of the basic data types, such as int, char, float, or double. To define a constant in C, you need to provide the following information:
1. Data type: The data type specifies the type of value that the constant can hold, such as int, char, float, or double.
2. Constant name: The constant name is used to refer to the constant in the program.
3. Initial value: You must initialize a constant to a specific value when you define it.
Here’s an example of how to define and use constants in C:
#includeint main() { const int AGE = 25; // Define a constant int named AGE and initialize it to 25 const char GRADE = 'A'; // Define a constant char named GRADE and initialize it to 'A' const float PI = 3.14; // Define a constant float named PI and initialize it to 3.14 const double SALARY = 50000; // Define a constant double named SALARY and initialize it to 50000 printf("I am %d years old\n", AGE); // Print the value of AGE printf("My grade is %c\n", GRADE); // Print the value of GRADE printf("The value of pi is %.2f\n", PI); // Print the value of PI with 2 decimal places printf("My salary is $%.2f\n", SALARY); // Print the value of SALARY with 2 decimal places return 0; }
In this example, we define four constants of different data types and initialize them to specific values. We then use the printf function to print the values of the constants to the console. Note that the const keyword is used to indicate that the values of the variables cannot be changed.