Understanding Constants in “C”: A Simple Guide

In C, a constant is a value that does not change during the execution of a program. You can define constants in two main ways:

1. Using the const Keyword:

The const keyword is used to declare a variable whose value cannot be changed after initialization.

#include <stdio.h>

int main() {
const int age = 25; // Declares a constant integer
printf(“Age: %d\n”, age);
// age = 30; // Error: Cannot modify a constant
return 0;
}

2. Using #define Preprocessor Directive:

The #define directive defines a constant value at the preprocessor level.

#include <stdio.h>

#define PI 3.14159 // Defines a constant PI

int main() {
printf(“Value of PI: %f\n”, PI);
// PI = 3.14; // Error: Cannot modify a #define constant
return 0;
}

Key Differences:

  • const is a variable with a specific type, which can be used with type checks and scope.
  • #define is a preprocessor macro, and it doesn’t have a type, making it more flexible but less safe.

For simple programs, both methods are widely used, but const is preferred for better type safety and debugging.

Leave a Comment

Your email address will not be published. Required fields are marked *