C Constants
1. What is a Constant?
-
A constant is a fixed value that cannot be altered by the program once defined.
-
Useful for values like pi, tax rates, maximum limits, or configuration values.
2. Types of Constants in C
| Type | Description | Example |
|---|---|---|
| Literal Constant | Directly written in code | 100, 3.14, 'A' |
| Symbolic Constant | Defined using #define or const keyword |
#define PI 3.14 or const int MAX = 100; |
3. Literal Constants
-
Integer constant:
10,-25 -
Floating-point constant:
3.14,-0.5 -
Character constant:
'A','9' -
String constant:
"Hello"
Example:
Output:
4. Symbolic Constants using #define
-
Use
#defineto give a name to a constant. -
Advantage: easier to update value in one place.
Output:
#definedoes not allocate memory; it’s a preprocessor directive.
5. Symbolic Constants using const Keyword
-
constdefines a typed constant. -
Memory is allocated, and value cannot be changed.
Output:
6. Key Points About Constants
-
Constants cannot be modified once defined.
-
#defineis handled by the preprocessor;constis a typed variable. -
Constants improve code readability and maintainability.
-
Use
constwhen you want type checking; use#definefor preprocessor constants.
7. Combined Example
Output:
