Preprocessor Directives in C

Preprocessor directives in C are commands that are executed by the preprocessor before the code is compiled. They are used to perform actions such as including header files, defining constants, and performing conditional compilation. Preprocessor directives are denoted by the `#` symbol at the beginning of a line of code.

Here are some commonly used preprocessor directives in C:

1. `#include`: This directive is used to include a header file in the source code. The syntax for using `#include` is:

#include 

Here, `header_file.h` is the name of the header file to be included. Header files typically contain function prototypes and type definitions that are needed by the source code.

2. `#define`: This directive is used to define a constant or a macro. The syntax for using `#define` is:

#define CONSTANT_NAME constant_value

Here, `CONSTANT_NAME` is the name of the constant or macro, and `constant_value` is the value to be assigned to it.

For example:

#define PI 3.14159

This code defines a constant named `PI` with the value `3.14159`.

3. `#ifdef` and `#ifndef`: These directives are used to perform conditional compilation. The syntax for using `#ifdef` and `#ifndef` is:

#ifdef MACRO_NAME
  // code to be compiled if MACRO_NAME is defined
#endif

#ifndef MACRO_NAME
  // code to be compiled if MACRO_NAME is not defined
#endif

Here, `MACRO_NAME` is the name of a macro that may or may not be defined. If the macro is defined, the code between `#ifdef` and `#endif` is compiled; if it is not defined, the code is skipped. The `#ifndef` directive is used to test for the opposite condition.

For example:

#define DEBUG 1

#ifdef DEBUG
  printf("Debugging mode enabled.\n");
#else
  printf("Debugging mode disabled.\n");
#endif

This code checks whether the constant `DEBUG` is defined. If it is defined, the message “Debugging mode enabled.” is printed to the console; otherwise, the message “Debugging mode disabled.” is printed.

4. `#pragma`: This directive is used to provide additional information to the compiler. The syntax for using `#pragma` is:

#pragma pragma_name [pragma_arguments]

Here, `pragma_name` is the name of the pragma to be used, and `pragma_arguments` are the arguments to be passed to the pragma.

For example:

#pragma pack(1)
struct example {
  char c;
  int i;
};

This code uses the `#pragma pack` directive to specify that the `example` structure should be packed tightly without any padding bytes between its members.

It’s important to note that preprocessor directives are processed before the code is compiled, and therefore have no effect on the runtime behavior of the program. They are used to modify the behavior of the compiler during the compilation process.