C Constants
Syntax
Constants have a syntax of:
const [data_type] [variable_name] = value;
Example
#include <stdio.h>
int main() {
const int num_iterations = 5;
printf("The number of iterations is %d\n", num_iterations);
const float pi = 3.14159;
printf("The value of pi is %f\n", pi);
return 0;
}
Output
The output of the above program will be:
The number of iterations is 5
The value of pi is 3.141590
Explanation
A constant is a value that cannot be changed by the program during its execution. In C, constants can be defined using the const
keyword. A constant is a variable that is assigned a value at the time of its declaration and cannot be modified afterwards. Constants can be of various types, including integers, floating-point numbers, characters, and more.
Use
Constants are used in programming to make code more readable and maintainable. By using constants, you can declare a value once and use it throughout the program, making it easier to update and modify. Constants can also be used to prevent accidental modifications to a value that should remain the same throughout the program's execution.
Important Points
- Constants are defined using the
const
keyword. - Constants are declared at the beginning of the program and cannot be changed thereafter.
- Constants can be used in mathematical operations just like variables.
- Constants improve the readability and maintainability of the code by clearly defining the values being used in the program.
Summary
C constants provide a way to define values that cannot be changed during program execution. They are useful for making code more readable and maintainable. By defining a value once and using it throughout the program, constants make it easier to update and modify the program. Understanding how to define, declare, and use constants is an essential part of C programming.