Constants in C

In C programming, constants are fixed values that, once defined, do not change during the execution of a program. Constants are used to represent data that remains the same throughout the program, ensuring that the values are not accidentally modified. Using constants helps improve code readability and maintainability.

Types of Constants in C

C provides several types of constants, including:

Detailed Explanation of Different Types of Constants

1. Integer Constants

Integer constants are used to represent whole numbers in the program. They can be written in decimal, octal, or hexadecimal format. Examples:

2. Floating-Point Constants

Floating-point constants represent real numbers with fractional parts. They can also be expressed in exponential notation for very large or small values. Examples:

3. Character Constants

Character constants represent single characters enclosed in single quotes. They are internally stored as integers (ASCII values). Examples:

4. String Constants

String constants are sequences of characters enclosed in double quotes. They are automatically null-terminated (i.e., they end with a '0' character). Examples:

5. Symbolic Constants

Symbolic constants are user-defined constants that improve the readability of code. You can define them using the #define directive or the const keyword. Examples:

Code Example: Defining Symbolic Constants


#include <stdio.h>
#define PI 3.14159 // Symbolic constant using #define
int main() {
    const int MAX_SCORE = 100; // Symbolic constant using const
    printf("Value of PI: %.5f\n", PI);
    printf("Max Score: %d\n", MAX_SCORE);
    return 0;
}

Output

Value of PI: 3.14159 Max Score: 100

Explanation of Code Example:

In the above code:

Benefits of Using Constants