C Macros

C Macros and Preprocessor Directives

The C Preprocessor is not part of the compiler itself, but rather a separate step that happens before compilation. It processes directives (commands starting with #) to include files, conditionally compile code, and define Macros.

A Macro is a fragment of code that has been given a name. Whenever the name is used, it is replaced by the contents of the macro.


1. Object-Like Macros

The most common use of #define is to create named constants. This makes your code highly readable and easy to modify.

Constant Macro Example:

#include <stdio.h>

#define PI 3.14159 #define MAX_USERS 100

int main() { double radius = 5.0; double area = PI * radius * radius; printf("Max users allowed: %d\n", MAX_USERS); printf("Area of circle: %.2f\n", area); return 0; }


2. Function-Like Macros

Macros can also take arguments, similar to functions. However, they do not have the overhead of a function call (like pushing variables to the stack). The preprocessor simply replaces the text inline.

Function-Like Macro Example:

#include <stdio.h>

// A macro to find the minimum of two numbers #define MIN(a, b) ((a) < (b) ? (a) : (b))

int main() { int x = 10, y = 20; printf("The minimum is: %d\n", MIN(x, y)); return 0; }

Pro Tip: Always wrap macro arguments in parentheses (like (a)) to prevent unexpected operator precedence issues when expressions are passed into the macro!


3. Predefined Macros

ANSI C defines several standard macros that you can use anywhere in your code, which are extremely useful for debugging and logging.


Exercise

?

Which preprocessor directive is used to define a macro in C?