Constants in C - Explained for Beginners


Introduction

In C programming, constants are values that cannot be changed during the execution of a program. They are used to represent fixed or unchanging values. Understanding constants is essential for writing programs that involve fixed values or settings. In this tutorial, we will explore constants in C and how to use them effectively.


Types of Constants

C supports different types of constants:

  • Integer Constants: Represent whole numbers, e.g., 42
  • Real Constants: Represent real numbers (floating-point), e.g., 3.14
  • Character Constants: Represent single characters, enclosed in single quotes, e.g., 'A'
  • String Constants: Represent sequences of characters, enclosed in double quotes, e.g., "Hello, World!"
  • Enumeration Constants: User-defined constants, part of an enumeration, e.g., enum Days { MON, TUE, WED };
  • Symbolic Constants: Named constants defined using the #define preprocessor directive, e.g., #define PI 3.14

Using Constants

Constants are used in C to make programs more readable, maintainable, and flexible. They can be used in various ways:

#include <stdio.h>
#define PI 3.14
int main() {
const int hoursInDay = 24;
float radius = 5.0;
float area = PI * radius * radius;
printf("There are %d hours in a day.\\n", hoursInDay);
printf("The area of a circle with radius %.2f is %.2f.\\n", radius, area);
return 0;
}

In this example, we use symbolic constants (PI) defined using the #define directive and a constant variable (hoursInDay) declared with the const keyword. These constants are used to calculate and display values.


Conclusion

Constants play a vital role in C programming by allowing you to represent fixed values clearly and maintainable. You've learned about various types of constants, including symbolic constants, and how to use them in your C programs. As you continue your journey, you'll find constants to be a valuable tool in your coding projects.