🎓 Lecture Article: Constants in C Programming
What Are Constants?
In C programming, a constant is a value that does not change during the execution of a program. Think of constants as read-only variables.
🧠 Why Use Constants?
- To store fixed values like Pi (3.1416), limits, etc.
- To make code easier to read and maintain
- To avoid accidental changes to important values
🔢 Types of Constants in C
C supports several types of constants:
- Integer Constants:
10, -25, 0 - Floating-point Constants:
3.14, -0.005, 2.5e3 - Character Constants:
'A', 'z', '1', '\n' - String Constants:
"Hello", "C Language" - Enumeration Constants: Created using
enum
🧾 Defining Constants in C
✅ 1. Using #define Preprocessor Directive
#define PI 3.14159 #define MAX_LIMIT 100
These are replaced during preprocessing. No data type is specified.
✅ 2. Using const Keyword
const float pi = 3.14159; const int maxUsers = 100;
This approach defines typed, read-only variables.
⚖️ #define vs const
| Feature | #define | const |
|---|---|---|
| Data type | No | Yes |
| Scope | Global | Follows block scope |
| Error checking | Less strict | Strict (type-checked) |
| Debugging | Harder (symbol not retained) | Symbols visible to debugger |
📘 Example Program
#include <stdio.h>
#define PI 3.14159
int main() {
const int radius = 5;
float area = PI * radius * radius;
printf("Area of circle: %.2f\n", area);
// radius = 10; // ❌ Error: read-only variable
return 0;
}
❌ Common Mistakes
- Trying to change a
constvalue after declaration - Using incorrect case:
Constinstead ofconst - Using
#defineinside functions (allowed, but poor style)
💡 Best Practices
- Use
constfor typed constants - Use
#definefor compile-time constants - Name constants in uppercase:
MAX_SIZE,PI
📝 Summary
- Constants are fixed values in C
- Defined using
#defineorconst - They improve code safety and clarity
- Various constant types: integer, float, char, string, enum
🎯 Practice Exercise
- Write a program to calculate circumference using a constant PI
- Define 3 constants using
#defineandconst - Try to modify a const value and observe the error
- Create an
enumfor the days of the week
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন