In C programming, constants are values that do not change during the execution of a program. They represent fixed values that are used throughout the program and help in making the code more readable and maintainable. Constants can be of various types, such as integers, floating-point numbers, characters, and strings.
1. Enhanced Readability: Constants provide meaningful names to fixed values, making the code easier to understand and modify.
2. Avoid Magic Numbers: Constants prevent the use of hard-coded values (magic numbers) in the code, which enhances readability and maintenance.
3. Reusability: Constants can be reused throughout the program, reducing the likelihood of errors due to inconsistent values or typos.
4. Optimization: Certain constants, such as mathematical constants, can optimize calculations or processes within the program.
Here are the different types of constants you can use in C:
| Constant Type | Example | Description |
|---|---|---|
| Decimal Constant | 10, 20, 450 | Represents whole numbers in decimal form. |
| Real or Floating-point Constant | 10.3, 20.2, 450.6 | Represents numbers with decimal points. |
| Octal Constant | 021, 033, 046 | Represents numbers in octal (base 8) form, prefixed with 0. |
| Hexadecimal Constant | 0x2a, 0x7b, 0xaa | Represents numbers in hexadecimal (base 16) form, prefixed with 0x. |
| Character Constant | 'a', 'b', 'x' | Represents a single character enclosed in single quotes. |
| String Constant | "c", "c program", "c in javatpoint" | Represents a sequence of characters enclosed in double quotes. |
1. const keyword
2. #define preprocessor
The const keyword is used to define a constant variable. Once a constant is initialized, its value cannot be changed throughout the program.
const data_type constant_name = value;
<#include <stdio.h>>
int main() {
const int MAX_SIZE = 100; // Define a constant integer
const float PI = 3.14; // Define a constant floating-point number
const char GRADE = 'A'; // Define a constant character
printf("Max Size: %d\\n", MAX_SIZE);
printf("PI: %.2f\\n", PI);
printf("Grade: %c\\n", GRADE);
return 0;
}
The #define directive is used to create symbolic constants or macros. The #define does not allocate memory and simply replaces the occurrences of the symbolic name with its value.
#define NAME value
<#include <stdio.h>>
#define MAX_SIZE 100 // Define a symbolic constant
#define PI 3.14 // Define a symbolic constant
#define GRADE 'A' // Define a symbolic constant
int main() {
printf("Max Size: %d\\n", MAX_SIZE);
printf("PI: %.2f\\n", PI);
printf("Grade: %c\\n", GRADE);
return 0;
}