Preprocessor in C

What is Preprocessor in C ?

In C programming, a preprocessor is a program that processes the source code before it is passed to the compiler. It performs various tasks like including files, defining constants, and conditional compilation. The preprocessor directives are lines in your code that start with a # symbol.

Include Directive (#include)

The #include directive is used to include the contents of a header file in your source code. It allows you to reuse code and declarations from other files. For example:

#include <stdio.h> // Includes the standard input/output header file

Define Directive (#define)

The #define directive is used to create macros, which are like shorthand for longer code snippets or values. Macros are replaced with their definitions during preprocessing. For instance:

#define PI 3.14159

Conditional Compilation Directives (#ifdef, #ifndef, #else, #elif, #endif)

Conditional compilation directives allow you to conditionally include or exclude sections of code from compilation based on certain conditions. Here’s an example:

#ifdef DEBUG
// Debugging code here
#endif

Macro Expansion

The preprocessor replaces macro names with their definitions throughout the code before compilation. For example:

float circle_area = PI * radius * radius;

Stringizing Operator (#)

The # operator can be used within macros to turn macro arguments into string literals. Here’s how it works:

#define STRINGIFY(x) #x
printf("Value of x: %s\n", STRINGIFY(42));

Token Pasting Operator (##)

The ## operator can be used within macros to concatenate tokens together. For example:

#define CONCAT(a, b)  ## b
int result = CONCAT(10, 20); // This becomes int result = 1020;