Constants in C
In C, constants are fixed values that do not change during the execution of a program. Once a constant is defined, its value cannot be modified.
Constants are used to represent fixed values such as
PI = 3.14, number of days in a week, or maximum limits.
They make programs easier to read and manage.
Syntax:
const data_type CONSTANT_NAME = value;
Why Use Constants?
- To store fixed values in a program.
- To prevent accidental changes in important values.
- To improve readability and maintainability of code.
Types of Constants in C
| Type | Description | Example |
|---|---|---|
| Integer Constants | Whole numbers without decimal point | 10, -50, 200 |
| Floating Point Constants | Numbers with decimal values | 3.14, -0.25 |
| Character Constants | Single character enclosed in single quotes | 'A', 'z' |
| String Constants | Characters enclosed in double quotes | "Hello", "C Notes" |
| Symbolic Constants | Constants created using const or #define |
const int MAX = 100; #define PI 3.14 |
Rules for Defining Constants
- Constants defined using
constshould be initialized at the time of declaration. - Once assigned, their values cannot be changed.
- Constants can be defined using const keyword or #define.
- Constant names are usually written in uppercase for readability
Example Program using Constants
// Program using constants in C
#include <stdio.h>
int main() {
const int DAYS = 7;
printf("Days in a week = %d", DAYS);
// DAYS = 10; // Invalid: cannot change constant value
return 0;
}
Output:
Days in a week = 7
Explanation:
DAYSis a constant created using theconstkeyword.- The value of
DAYScannot be changed during program execution. DAYS = 10;gives an error because constants are read-only values.
Real-Life Analogy:
Think of constants like your date of birth. Once fixed, it does not change. Similarly, constants in C store values that remain unchanged throughout the program.
Common Mistakes with Constants
- Trying to change the value of a constant later in the program.
- Forgetting to initialize constants during declaration.
- Confusing character constants with string constants.
- Using lowercase names for constants, which reduces readability.
Summary:
- Constants are fixed values that cannot be changed during program execution.
- Types of constants include integer, float, character, string, and symbolic constants.
- Constants can be created using
constand#define. - Constants improve readability and prevent accidental changes in values.