In C programming language, a constant is a value that cannot be altered during the execution of the program. Constants can be used to define fixed values that are used repeatedly in a program. In this article, we will discuss constants in C, their types, and how to declare and use them in a program.
Constants in C
Constants in C are values that cannot be modified during the execution of a program. They are typically defined using the const
keyword.
Types of Constants:
-
Literal Constants: These are directly written values within the code, such as numbers, characters, or strings.
- Integer literals:
10
,-5
,0x123
(hexadecimal),0b101
(binary),012
(octal) - Floating-point literals:
3.14
,1.2e5
(scientific notation) - Character literals:
'A'
,'\n'
(newline),'\t'
(tab) - String literals:
"Hello, world!"
- Integer literals:
-
Symbolic Constants: These are named constants defined using the
#define
preprocessor directive. #define PI 3.14159
Example:
#define MAX_LENGTH 100
int main() {
const int age = 25;
char name[MAX_LENGTH] = "Alice";
// You cannot modify age or MAX_LENGTH
// age = 30; // Error
// MAX_LENGTH = 200; // Error
printf("Name: %s, Age: %d\n", name, age);
return 0;
}
Advantages of Using Constants:
- Readability: Constants make code more readable by giving meaningful names to values.
- Maintainability: If you need to change a constant value, you only need to modify its definition, reducing the chances of errors.
- Efficiency: In some cases, the compiler can optimize code based on constant values, improving performance.
Best Practices:
- Use uppercase names for symbolic constants to distinguish them from variables.
- Use meaningful names that clearly indicate the purpose of the constant.
- Avoid modifying constants during runtime.