Macros in C Language
Introduction
Macros are a feature of the C preprocessor that allow you to define symbolic constants or expressions. They are a powerful tool for extending the functionality of your programs and making your code more readable and maintainable.
Defining a Macro
To define a macro, you use the #define directive followed by the name of the macro and its definition.
In this example, PI is defined as 3.14159. Whenever the preprocessor encounters PI in the code, it replaces it with 3.14159.
Macros with Arguments
Macros can also take arguments, allowing for more flexible and reusable code.
In this example, SQUARE is a macro that takes one argument (x) and returns its square.
Example usage:
#include <stdio.h> #define SQUARE(x) ((x) * (x)) int main() { int num = 5; printf("Square of %d is %d\n", num, SQUARE(num)); return 0; }
Square of 5 is 25
Conditional Compilation
Macros can be used for conditional compilation, which allows different parts of the code to be compiled depending on certain conditions.
#include <stdio.h> #define DEBUG 1 int main() { #if DEBUG printf("Debug mode is ON\n"); #endif printf("Program is running\n"); return 0; }
Debug mode is ON
Program is running
Undefining Macros
You can undefine a macro using the #undef directive.
#include <stdio.h> #define MESSAGE "Hello, World!" int main() { printf("%s\n", MESSAGE); #undef MESSAGE // MESSAGE is undefined here return 0; }
Hello, World!
Predefined Macros
The C preprocessor provides several predefined macros. Some of the most commonly used ones are:
- __DATE__ - The current date as a string literal in the form "MMM DD YYYY".
- __TIME__ - The current time as a string literal in the form "HH:MM:SS".
- __FILE__ - The current filename as a string literal.
- __LINE__ - The current line number as a decimal constant.
- __STDC__ - Defined as 1 when the compiler complies with the ANSI standard.
#include <stdio.h> int main() { printf("File: %s\n", __FILE__); printf("Date: %s\n", __DATE__); printf("Time: %s\n", __TIME__); printf("Line: %d\n", __LINE__); return 0; }
File: example.c
Date: MMM DD YYYY
Time: HH:MM:SS
Line: 8
Conclusion
Macros are a powerful feature in the C language that provide a way to make your code more flexible, readable, and maintainable. By understanding how to define and use macros, you can enhance your programming skills and create more efficient and effective C programs.