C Constants

๐Ÿ”’ C Constants – Fixed Values in C Programming

In C, constants are fixed values that do not change during the execution of a program. They help keep your code secure and prevent accidental modification of important values.

๐Ÿ”น Types of Constants

  • Literal Constants โ€“ Direct values like 100, 'A', 3.14
  • Symbolic Constants โ€“ Defined using #define
  • Constant Variables โ€“ Declared using const keyword

๐Ÿ“ Example: Using const Keyword

This example shows how to declare a constant using the const keyword.

#include <stdio.h>

int main() {
    const float PI = 3.14159;
    printf("Value of PI: %.5f\n", PI);

    // PI = 3.14; // โŒ This will cause an error because PI is constant
    return 0;
}
  

Try It Now

๐Ÿ“ Example: Using #define Macro

This example uses a macro to define a symbolic constant.

#include <stdio.h>

#define MAX_USERS 100

int main() {
    printf("The system can support up to %d users.\n", MAX_USERS);
    return 0;
}
  

Try It Now

๐ŸŽฏ Const vs #define

Feature const #define
Type Checking โœ”๏ธ Yes โŒ No
Memory Allocation โœ”๏ธ Allocates memory โŒ No memory allocation
Scope Follows variable scope Global

๐Ÿง  Quick Tips

  • Use const when you need type safety.
  • Use #define for global constants or preprocessor configs.

๐ŸŽ‰ Practice Task

Try creating constants for gravity (9.8), speed of light, and your lucky number. Print them in a program!