Constants in C

Constants are fixed values that cannot be changed during program execution. They are used to make programs more readable, maintainable, and less error-prone. In C, constants can be numeric, character, or symbolic.

Types of Constants in C

  • Integer Constants: Whole numbers without decimals. Example: 10, -5, 0
  • Floating-point Constants: Numbers with decimal points. Example: 3.14, -0.5
  • Character Constants: Single characters enclosed in single quotes. Example: 'A', '9', '\n'
  • String Constants (Literals): Sequence of characters enclosed in double quotes. Example: "Hello World"
  • Symbolic Constants: Named constants defined using the #define directive or const keyword. Example: #define PI 3.14159 or const int MAX = 100

Declaring Constants

  • Using #define: #define PI 3.14159 // Symbolic constant
  • Using const keyword: const int MAX = 100; // Constant integer
  • Character constant: char grade = 'A';
  • Floating constant: float tax = 0.05;

Importance of Constants

  • Improve program readability by giving meaningful names to fixed values.
  • Prevent accidental modification of values during program execution.
  • Make programs easier to maintain, especially when constants are used in multiple places.
  • Help reduce errors caused by hard-coded values.

Examples of Constants in Use

  • #define PI 3.14159 // Symbolic constant float area = PI * radius * radius;
  • const int MAX = 100; // Constant integer for (int i = 0; i < MAX; i++) { ... }
  • char grade = 'A'; // Character constant
  • float tax = 0.05; // Floating-point constant

Conclusion

Constants are an essential part of C programming. They provide fixed values that improve code readability, maintainability, and reliability.

By using constants wisely, programmers can avoid errors, simplify updates, and write more robust programs.