Constants in C Programming

🎓 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 const value after declaration
  • Using incorrect case: Const instead of const
  • Using #define inside functions (allowed, but poor style)

💡 Best Practices

  • Use const for typed constants
  • Use #define for compile-time constants
  • Name constants in uppercase: MAX_SIZE, PI

📝 Summary

  • Constants are fixed values in C
  • Defined using #define or const
  • They improve code safety and clarity
  • Various constant types: integer, float, char, string, enum

🎯 Practice Exercise

  1. Write a program to calculate circumference using a constant PI
  2. Define 3 constants using #define and const
  3. Try to modify a const value and observe the error
  4. Create an enum for the days of the week

একটি মন্তব্য পোস্ট করুন