Constants and Macros in C


Introduction

Constants and macros are essential in C programming to define values that should not change during the program's execution. They provide a way to make code more readable, maintainable, and adaptable. In this guide, we'll explore how to work with constants and macros in C and provide sample code to illustrate their usage.


Constants

Constants are values that do not change during the program's execution. In C, there are two primary ways to define constants:

  • Using #define: You can use the preprocessor directive #define to create symbolic constants. These are replaced by their values during compilation.
  • Using const Keyword: You can use the const keyword to declare variables as constants. These variables have read-only values.

Macros

Macros are preprocessor directives that allow you to define reusable code snippets. They are commonly used for defining constants, inline functions, or conditional compilation. Macros are defined using the #define directive and are replaced by their code during compilation.


Sample Code

Let's explore some examples of working with constants and macros in C:


Constants Defined with #define

#include <stdio.h>
#define PI 3.14159265359
#define MAX_VALUE 100
int main() {
double radius = 5.0;
double area = PI * radius * radius;
printf("Area of a circle: %f\\n", area);
printf("Max allowed value: %d\\n", MAX_VALUE);
return 0;
}

Constants Defined with const Keyword

#include <stdio.h>
int main() {
const double PI = 3.14159265359;
const int MAX_VALUE = 100;
double radius = 5.0;
double area = PI * radius * radius;
printf("Area of a circle: %f\\n", area);
printf("Max allowed value: %d\\n", MAX_VALUE);
return 0;
}

Macros for Code Reuse

#include <stdio.h>
#define SQUARE(x) (x * x)
int main() {
int number = 5;
int squared = SQUARE(number);
printf("Square of %d is %d\\n", number, squared);
return 0;
}

Conclusion

Constants and macros are valuable tools in C programming for defining values that should not change and for creating reusable code snippets. This guide has introduced you to constants and macros, explaining how to define them using #define and the const keyword. Sample code demonstrates their usage. As you continue your C programming journey, you'll find constants and macros to be crucial for writing clean, maintainable code.