
Constants and Literals in C
Understanding constants and literals helps write more stable and efficient C programs.
"Constants ensure that values remain unchanged, making programs more predictable and error-free."
Types of Constants in C
1. Integer Constants
Whole numbers without a decimal point. They can be decimal, octal (prefixed with 0
), or hexadecimal (prefixed with 0x
).
int decimal = 100;
int octal = 0123; // Octal (Equivalent to 83 in decimal)
int hex = 0x1A; // Hexadecimal (Equivalent to 26 in decimal)
2. Floating-Point Constants
Numbers with a decimal point or in exponent notation.
float pi = 3.1415;
double largeNumber = 1.23e5; // Equivalent to 1.23 × 10^5
3. Character Constants
A single character enclosed in single quotes.
char letter = 'A';
char newline = '\n'; // Escape sequence for new line
4. String Constants (Literals)
A sequence of characters enclosed in double quotes.
char greeting[] = "Hello, C!";
5. Boolean Constants (C99 and later)
Represents true
or false
. Requires #include <stdbool.h>
.
#include <stdbool.h>
bool isActive = true;
Declaring Constants in C
1. Using the const
Keyword
Declares a read-only variable.
const float PI = 3.1415;
const int MAX_USERS = 100;
2. Using the #define
Preprocessor Directive
Defines constant values without a data type.
#define PI 3.1415
#define MAX_USERS 100
Difference Between Constants and Variables
Feature | Constants (const ) |
Variables |
---|---|---|
Value Change | Cannot change after declaration | Can change anytime |
Memory Usage | Stored in read-only memory | Stored in normal memory |
Scope | Can be local or global | Can be local, global, or static |
Code Example: Using Constants in C
#include <stdio.h>
#define PI 3.1415
int main() {
const int maxScore = 100;
printf("The value of PI is: %f\n", PI);
printf("The maximum score is: %d\n", maxScore);
return 0;
}
Why Use Constants?
- Prevents accidental modifications
- Improves code readability
- Enhances program efficiency and maintainability
By using constants and literals effectively, you ensure your C programs are reliable, optimized, and easy to debug! 🚀