C Tutorial



CONSTANTS IN C


Constants in C

Constants in C are fixed values that do not change during the execution of a program. Once defined, a constant cannot be altered.

๐Ÿ” Why Use Constants? They improve code readability, prevent accidental changes, and make maintenance easier.

โœ๏ธ Declaring Constants

  • Using const keyword: Declares a variable as constant.
  • Using #define preprocessor: Defines a constant value globally.

๐Ÿงช Example

#include <stdio.h>

#define PI 3.14  // Constant using #define

int main() {
    const int MAX = 100;  // Constant using const keyword

    printf("PI is: %f\\n", PI);
    printf("Max limit is: %d\\n", MAX);

    return 0;
}
  

โœ… Key Points

  • const is type-safe and preferred for variables.
  • #define is a preprocessor directive and has no type.
  • You can't change the value of a constant after its definition.
๐Ÿ’ก Tip: Use meaningful names for constants, e.g., MAX_SPEED, PI, etc.

โŒ Common Mistakes

  • ๐Ÿšซ Trying to change the value of a constant after declaring it.
  • ๐Ÿšซ Forgetting semicolon after const declaration.

๐Ÿ“ Try It Yourself

  1. Declare a constant using const to store the maximum marks in a test.
  2. Define a constant using #define for the value of gravity (e.g., 9.8).

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review