The Wayback Machine - https://web.archive.org/web/20240828110659/https://www.geeksforgeeks.org/cpp-preprocessor-directives-set-2/
Open In App

C Preprocessor Directives

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In almost every C program we come across, we see a few lines at the top of the program preceded by a hash (#) sign. They are called preprocessor directives and are preprocessed by the preprocessor before actual compilation begins. The end of these lines is identified by the newline character ‘\n’, no semicolon ‘;’ is needed to terminate these lines. Preprocessor directives are mostly used in defining macros, evaluating conditional statements, source file inclusion, pragma directives, line control, error detection, etc.

List of Preprocessor Directives in C

The following table lists all the preprocessor directives available in the C programming language:

Preprocessor Directives

Description

#define

Used to define a macro.

#undef

Used to undefine a macro.

#include

Used to include a file in the source code program.

#ifdef

Used to include a section of code if a certain macro is defined by #define.

#ifndef

Used to include a section of code if a certain macro is not defined by #define.

#if

Check for the specified condition.

#else

Alternate code that executes when #if fails.

#endif

Used to mark the end of #if, #ifdef, and #ifndef.

#error

Used to generate a compilation error message.

#line

Used to modify line number and filename information.

#pragma once

To make sure the header is included only once.

#pragma message

Used for displaying a message during compilation.

Types of Preprocessor Directives in C

In C, preprocessor directives are categorized based on their functionalities following are the types of preprocessor directives:

  1. Macro Definition
  2. File Inclusion directive
  3. Conditional Compilation
  4. Line control
  5. Error directive
  6. Pragma direcive

Let us now have a look at each one of these directives in detail:

1. #define – Macro Directive

In C, macro definition directives uses the #define preprocessor directive to define the macros and symbolic constants. We use #define directive to define macro. Macro are basically the symbolic names that represents lines of code or some values. This directive is used to create constants or to define short, reusable codes.

Syntax

#define token value

Example

C
// C program to illustrate the use of #define directive
#include <stdio.h>

// Defining a macro for PI
#define PI 3.14159

int main()
{
    // Using the PI macro to calculate
    double radius = 8.0;
    double area = PI * radius * radius;

    // Displaying the calculated area
    printf("Area of the circle is: %f\n", area);

    return 0;
}

Output
Area of the circle is: 201.061760

2. #include – File Inclusion Directive

#include is one of the file inclusion directive in C. #include preprocessor directive is used to include the content of one file to another file i.e. source code during the preprocessing stage. This is done to easily organize the code and increase the reusability of code.

Syntax

#include <file_name>
or
#include "filename"

Here, file inclusion with double quotes ( ” ” ) tells the compiler to search for the header file in the directory of source file.

Example

The below example demonstrates the use of file inclusion directive #include.

C
// C program to demonstrate the use of file inclusion
// directive #include.

#include <stdio.h> // includng header file for Standard input/output functions
#include <stdlib.h> // includng header file for Standard library functions

int main()
{
    // Using  standard input/output functions from stdio.h
    printf("Hello, Geek!\n");

    // Using standard library functions
    int num1 = 10, num2 = 5;
    int sum = num1 + num2;

    // displayng the result using printf from stdio.h
    printf("Sum: %d\n", sum);
    return 0;
}

Output
Hello, Geek!
Sum: 15

3. #if, #ifdef, #else, #elif, #endif – Conditional Compilation

Conditional Compilation directives help to compile a specific portion of the program or let us skip compilation of some specific part of the program based on some conditions. In our C Preprocessors article, we have discussed about such directives.

#ifdef: This directive is the simplest conditional directive. This block is called a conditional group. The controlled text will get included in the preprocessor output if the macroname is defined. The controlled text inside a conditional will embrace preprocessing directives. They are executed only if the conditional succeeds. You can nest these in multiple layers, but they must be completely nested. In other words, ‘#endif’ always matches the nearest ‘#ifdef’ (or ‘#ifndef’, or ‘#if’). Also, you can’t begin a conditional group in one file and finish it in another. 

Syntax

#ifdef MACRO
controlled text
#endif

#ifndef: In #ifdef directive if the macroname is defined, then the block of statements after the #ifdef directive will be executed normally but in case it is not defined, the compiler will simply skip this block of statements. The #ifndef directive is simply the opposite of #ifdef directive. In case of #ifndef , the block of statements between #ifndef and #endif will get executed only if the macro or the identifier with #ifndef is not defined. 

Syntax

ifndef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
endif

Note: If the macro with name as ‘macroname‘ is not defined using the #define directive then only the block of statements will execute.

#if, #else and #elif: All these directives works together and control compilation of portions of the program using some conditions. If the condition with the #if directive results in a non zero value, then the group of line immediately after the #if directive will be executed otherwise if the condition with the #elif directive evaluates to a non zero value, then the group of line immediately after the #elif directive will be executed else the lines after #else directive will be executed. 

Syntax

#if macro_condition
statements
#elif macro_condition
statements
#else
statements
#endif

Example

The below example demonstrates the use of conditional directives.

C
// C program to demonstrate the use of conditional
// directives.

#include <stdio.h>

#define gfg 7

#if gfg > 200
#undef gfg
#define gfg 200
#elif gfg < 50
#undef gfg
#define gfg 50
#else
#undef gfg
#define gfg 100
#endif

void printValue(int value) { printf("%d", value); }

int main()
{
    printValue(gfg); // gfg = 50
    return 0;
}

Output
50

Note: the entire structure of #if, #elif and #else chained directives ends with #endif.

4. #line – Line Control

Whenever we compile a program, there are chances of occurrence of some error in the program. Whenever compiler identifies error in the program it provides us with the filename in which error is found along with the list of lines and with the exact line numbers where the error is. This makes easy for us to find and rectify error. However we can control what information should the compiler provide during errors in compilation using the #line directive. 

Syntax

#line number "filename"

number – line number that will be assigned to the next code line. The line numbers of successive lines will be increased one by one from this point on. “filename” – optional parameter that allows to redefine the file name that will be shown.

Example

C
// C program to demonstrate the use of #line

#include <stdio.h>

// Macro to print the current line number
#define PrintLineNum                                       \
    printf("Line number is %d in file named %s\n",         \
           __LINE__, __FILE__)

int main()
{
    // Print the original line number
    PrintLineNum;

// Using #line to change line number and file name
// temporarily
#line 20 "main.c"
    PrintLineNum;

// revert to the original line number and file name
#line 30 "index.c"
    PrintLineNum;

    return 0;
}

Output
Line number is 13 in file named ./Solution.c
Line number is 20 in file named main.c
Line number is 30 in file named index.c

5. #error – Error Directive

The #error directive aborts the compilation process when it is found in the program during compilation and produces an error which is optional and can be specified as a parameter. 

Syntax

#error optional_error

Here, optional_error is any error specified by the user which will be shown when this directive is found in the program.

Example

The below example demonstrate the use of error directive to display custom error message.

C
// C program to demonstrate the use of error directive to
// display custom error message.

#include <stdio.h>

// #define GeeksforGeeks  // not Defining the symbol
// GeeksforGeeks

#ifndef GeeksforGeeks
#error GeeksforGeeks not found!
#endif

int main()
{
    printf("Hello, GeeksforGeeks!\n");
    return 0;
}


Output

error: #error GeeksforGeeks not found !

6. #pragma – Pragma directive

The #pragma directive is used to provide the compiler some extra information and hence it is compiler dependent so we can say that it’s behavior vary according to the compiler we are using. The pragma directive basically gives the instructions to the compiler to turn on or turn off some feature and also to give some custom messages required.

Syntax

#pragma directive

Commonly used pragma directives are:

  • #pragma message: used at compile time to print custom messages.
  • #pragma once: to guard the header files i.e the header file must be included only once.
  • #pragma warning: to enable or disable the warnings.

Example

The below example demonstrates the use of pragma directive to display the custom message.

C
// C program to illustrate the use of Pragma to print the
// custom message

#include <stdio.h>

// not defining gfg to trigger pragma message
// #define GeeksforGeeks

int main()
{
#ifndef GeeksforGeeks
#pragma message(" GfG is not defined.")
#endif
    printf("Hello geek!\n");
    return 0;
}


Output

#pragma message:  GfG is not defined.


Previous Article
Next Article

Similar Reads

C++ Preprocessor And Preprocessor Directives
The preprocessor in C++ is used for processing the code before it is compiled by the compiler. It does many tasks such as including files, conditional compilation, using macros, etc. The preprocessor also allows the developers to select which portions of code should be included or excluded. The code processed by the preprocessor is called expanded
7 min read
C | Macro &amp; Preprocessor | Question 1
#include &lt;stdio.h&gt; #define PRINT(i, limit) do \ { \ if (i++ &lt; limit) \ { \ printf(&quot;GeeksQuiz\n&quot;); \ continue; \ } \ }while(1) int main() { PRINT(0, 3); return 0; } How many times GeeksQuiz is printed in the above program? (A) 1 (B) 3 (C) 4 (D) Compile-time error Answer: (D) Explanation: The PRINT macro gets expanded at the pre-pr
1 min read
C | Macro &amp; Preprocessor | Question 2
C/C++ Code #include #if X == 3 #define Y 3 #else #define Y 5 #endif int main() { printf(\"%d\", Y); return 0; } What is the output of the above program? (A)3 (B)5 (C)3 or 5 depending on value of X (D)Compile time error Answer: (B)Explanation: In the first look, the output seems to be compile-time error because macro X has not been defined. In C, if
1 min read
C | Macro &amp; Preprocessor | Question 14
What is the output of following program? C/C++ Code #include #define macro(n, a, i, m) m##a##i##n #define MAIN macro(n, a, i, m) int MAIN() { printf(\"GeeksQuiz\"); return 0; } (A) Compiler Error (B) GeeksQuiz (C) MAIN (D) main Answer: (B)Explanation: The program has a preprocessor that replaces \"MAIN\" with \"macro(n, a, i, m)\". The line \"macro
1 min read
C | Macro &amp; Preprocessor | Question 4
#include &lt;stdio.h&gt; #define X 3 #if !X printf(&quot;Geeks&quot;); #else printf(&quot;Quiz&quot;); #endif int main() { return 0; } (A) Geeks (B) Quiz (C) Compiler Error (D) Runtime Error Answer: (C) Explanation: A program is converted to executable using following steps 1) Preprocessing 2) C code to object code conversion 3) Linking The first s
1 min read
C | Macro &amp; Preprocessor | Question 5
#include &lt;stdio.h&gt; #define ISEQUAL(X, Y) X == Y int main() { #if ISEQUAL(X, 0) printf(&quot;Geeks&quot;); #else printf(&quot;Quiz&quot;); #endif return 0; } Output of the above program? (A) Geeks (B) Quiz (C) Any of Geeks or Quiz (D) Compile time error Answer: (A) Explanation: The conditional macro #if ISEQUAL(X, 0) is expanded to #if X == 0.
1 min read
C | Macro &amp; Preprocessor | Question 6
#include &lt;stdio.h&gt; #define square(x) x*x int main() { int x; x = 36/square(6); printf(&quot;%d&quot;, x); return 0; } (A) 1 (B) 36 (C) 0 (D) Compiler Error Answer: (B) Explanation: Preprocessor replaces square(6) by 6*6 and the expression becomes x = 36/6*6 and value of x is calculated as 36. Note that the macro will also fail for expressions
1 min read
C | Macro &amp; Preprocessor | Question 7
Output? # include &lt;stdio.h&gt; # define scanf &quot;%s Geeks Quiz &quot; int main() { printf(scanf, scanf); return 0; } (A) Compiler Error (B) %s Geeks Quiz (C) Geeks Quiz (D) %s Geeks Quiz Geeks Quiz Answer: (D) Explanation: After pre-processing phase of compilation, printf statement will become. printf("%s Geeks Quiz ", "%s Geeks Quiz "); Now
1 min read
C | Macro &amp; Preprocessor | Question 8
#include &lt;stdio.h&gt; #define a 10 int main() { printf(&quot;%d &quot;,a); #define a 50 printf(&quot;%d &quot;,a); return 0; } (A) Compiler Error (B) 10 50 (C) 50 50 (D) 10 10 Answer: (B) Explanation: Preprocessor doesn't give any error if we redefine a preprocessor directive. It may give warning though. Preprocessor takes the most recent value
1 min read
C | Macro &amp; Preprocessor | Question 9
Output? #include&lt;stdio.h&gt; #define f(g,g2) g##g2 int main() { int var12 = 100; printf(&quot;%d&quot;, f(var,12)); return 0; } (A) 100 (B) Compiler Error (C) 0 (D) 1 Answer: (A) Explanation: The operator ## is called “Token-Pasting” or “Merge” Operator. It merges two tokens into one token. So, after preprocessing, the main function becomes as f
1 min read
C | Macro &amp; Preprocessor | Question 10
Which file is generated after pre-processing of a C program? (A).p (B).i (C).o (D).m Answer: (B)Explanation: After the pre-processing of a C program, a .i file is generated which is passed to the compiler for compilation. Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
C | Macro &amp; Preprocessor | Question 11
What is the use of \"#pragma once\"? (A)Used in a header file to avoid its inclusion more than once. (B)Used to avoid multiple declarations of same variable. (C)Used in a c file to include a header file at least once. (D)Used to avoid assertions Answer: (A)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above
1 min read
C | Macro &amp; Preprocessor | Question 12
Predict the output of following program? #include &lt;stdio.h&gt; #define MAX 1000 int main() { int MAX = 100; printf(&quot;%d &quot;, MAX); return 0; } (A) 1000 (B) 100 (C) Compiler Error (D) Garbage Value Answer: (C) Explanation: After preprocessing stage of compilation, the function main() changes to following int main() { int 1000 = 100; // COM
1 min read
C | Macro &amp; Preprocessor | Question 13
Output of following C program? #include&lt;stdio.h&gt; #define max abc #define abc 100 int main() { printf(&quot;maximum is %d&quot;, max); return 0; } (A) maximum is 100 (B) abcimum is 100 (C) 100imum is 100 (D) abcimum is abc Answer: (A) Explanation: After pre-processing, the source code becomes: int main() { printf(&quot;maximum is %d&quot;, 100
1 min read
C | Macro &amp; Preprocessor | Question 14
#include &lt;stdio.h&gt; #define get(s) #s int main() { char str[] = get(GeeksQuiz); printf(&quot;%s&quot;, str); return 0; } (A) Compiler Error (B) #GeeksQuiz (C) GeeksQuiz (D) GGeeksQuiz Answer: (C) Explanation: The preprocessing operator '#' is used to convert a string argument into a string constant.Quiz of this Question
1 min read
C | Macro &amp; Preprocessor | Question 15
What is the output for the following code snippet? #include&lt;stdio.h&gt; #define A -B #define B -C #define C 5 int main() { printf(&quot;The value of A is %d\n&quot;, A); return 0; } This question is contributed by Aastha Anand. (A) The value of A is 4 (B) The value of A is 5 (C) Compilation Error (D) Runtime Error Answer: (B) Explanation: Value
1 min read
Convert C/C++ program to Preprocessor code
We use g++ compiler to turn provided Cpp code into preprocessor code. To see the preprocessor code generated by the CPP compiler, we can use the “-E” option on the command line: Preprocessor include all the # directives in the code. and also expands MACRO function. Syntax: g++ -E filename.cpp // MACRO named MAX initialism to 10 #define MAX 10 int m
1 min read
Debugging Using Preprocessor Directive in C
The C-compiler can detect only syntax errors whereas it cannot detect any run-time errors. So, this may produce an erroneous output if the run-time error persists. To detect the run-time errors, the programmer needs to debug the program before execution. But this debugging process becomes a quite tedious task if the program is bigger containing man
3 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C Programs
C Programs: Practicing and solving problems is the best way to learn anything. Here, we have provided 100+ C programming examples in different categories like basic C Programs, Fibonacci series in C, String, Array, Base Conversion, Pattern Printing, Pointers, etc. These C programs are the most asked interview questions from basic to advanced level.
9 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
10 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
9 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read