ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Preprocessor Directive…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    7 min read
    Topic 32 of 39
    Topic Study Note Illustration
    32

    Preprocessor: #include, #define, Conditional Compilation, #error and #pragma

    The C Preprocessor is a tool that processes your C code before the actual compilation begins. It handles directives that modify the source code based on specific...

    Preprocessor in C: #include, #define, Conditional Compilation, #error, and #pragma

    The C Preprocessor is a tool that processes your C code before the actual compilation begins. It handles directives that modify the source code based on specific conditions or external factors. Preprocessor directives are not C language statements but are instructions to the preprocessor, which are invoked by # symbols.

    1. #include: File Inclusion

    The #include directive is used to include external files into your C program. It is used to insert the contents of a file into your source code at the point where the #include directive is written.

    There are two common types of file inclusion:

    • Standard Library Header Files: These are files provided by the C standard library (like stdio.h, stdlib.h), and are included using angle brackets < >.

      #include <stdio.h>
      
    • User-Defined Header Files: These are files you create and save with the .h extension. They are included using double quotes " ".

      #include "myheader.h"
      

    Explanation:

    • The preprocessor will replace the #include directive with the content of the specified file, essentially copying it into the source code.
    • For example, #include <stdio.h> makes standard input/output functions (like printf() and scanf()) available in the program.

    Example:

    #include <stdio.h>
    
    int main() {
        printf("Hello, World!\n");
        return 0;
    }
    

    Here, #include <stdio.h> brings in the standard input/output functions provided by the C library.


    2. #define: Macros

    The #define directive is used to define macros, which are essentially simple text substitutions. A macro can be a constant or a function-like entity, allowing the preprocessor to replace occurrences of the macro in the code with its definition.

    Syntax:

    #define MACRO_NAME replacement_text
    

    Example:

    #define PI 3.14159
    #define AREA_OF_CIRCLE(radius) (PI * (radius) * (radius))
    
    #include <stdio.h>
    
    int main() {
        float radius = 5.0;
        printf("Area of circle: %.2f\n", AREA_OF_CIRCLE(radius));
        return 0;
    }
    

    Explanation:

    • #define PI 3.14159: Defines a constant PI to represent the value 3.14159.
    • #define AREA_OF_CIRCLE(radius) (PI * (radius) * (radius)): Defines a function-like macro to calculate the area of a circle.
    • The preprocessor will replace PI and AREA_OF_CIRCLE(radius) with their respective values at the point of usage, which improves readability and maintainability.

    3. Conditional Compilation

    Conditional compilation allows you to include or exclude portions of the code based on certain conditions. This is useful for platform-specific code, debugging, or code that needs to vary depending on different environments.

    Syntax:

    #if condition
        // Code to include if condition is true
    #else
        // Code to include if condition is false
    #endif
    

    Example:

    #include <stdio.h>
    
    #define DEBUG
    
    int main() {
        int x = 10;
    
        #ifdef DEBUG
            printf("Debugging: The value of x is %d\n", x);
        #endif
    
        printf("The value of x is %d\n", x);
        return 0;
    }
    

    Explanation:

    • #ifdef DEBUG checks if DEBUG is defined. If it is, the code inside the block is included.
    • If the macro DEBUG is not defined, the code in the #ifdef block will be ignored by the preprocessor.
    • Other conditional directives:
      • #if: Tests whether a condition is true (can be used for expressions).
      • #else: Provides an alternative code block if the condition is false.
      • #elif: Provides another condition if the initial #if or #ifdef fails.

    Example with #elif:

    #include <stdio.h>
    
    #define PLATFORM_LINUX
    
    int main() {
        #if defined(PLATFORM_WINDOWS)
            printf("Windows platform\n");
        #elif defined(PLATFORM_LINUX)
            printf("Linux platform\n");
        #else
            printf("Unknown platform\n");
        #endif
        return 0;
    }
    

    Here, based on the definition of PLATFORM_LINUX, the preprocessor will choose the appropriate block to include in the compiled code.


    4. #error: Generating Compilation Errors

    The #error directive is used to intentionally trigger a compilation error with a custom error message. This can be helpful for handling situations where the code shouldn't compile due to missing configurations or incorrect settings.

    Syntax:

    #error "Error message"
    

    Example:

    #include <stdio.h>
    
    #define VERSION 1
    
    int main() {
        #if VERSION < 2
            #error "This version is too old! Please upgrade."
        #endif
    
        printf("Welcome to the program!\n");
        return 0;
    }
    

    Explanation:

    • The #error directive is used to stop the compilation and display an error message if the VERSION is less than 2.
    • This prevents code from compiling if a certain condition is met, which is useful in ensuring the code runs under the expected configurations or versions.

    Output:

    error: "This version is too old! Please upgrade."
    

    5. #pragma: Compiler-Specific Directives

    The #pragma directive provides additional instructions to the compiler, often used to control compiler behavior or provide hints to the compiler. The behavior of #pragma can vary across different compilers.

    Syntax:

    #pragma directive_name [optional_arguments]
    

    Example: #pragma once

    One of the most common uses of #pragma is #pragma once, which ensures that a header file is included only once in a compilation unit, preventing multiple inclusions of the same header file.

    #pragma once
    // Contents of header file
    

    Example: Disabling Warnings

    Another common use of #pragma is to disable specific compiler warnings. Here's an example of disabling a warning in GCC or MSVC:

    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wunused-variable"
    
    int main() {
        int unused_var;
        printf("Hello, World!\n");
        
        #pragma GCC diagnostic pop
        return 0;
    }
    

    Explanation:

    • #pragma GCC diagnostic push saves the current state of diagnostics.
    • #pragma GCC diagnostic ignored "-Wunused-variable" disables warnings related to unused variables.
    • #pragma GCC diagnostic pop restores the previous diagnostic state.

    Other Pragma Directives:

    • #pragma once: Ensures the header file is included only once.
    • #pragma pack: Specifies the alignment of structure members.
    • #pragma warning: Used in some compilers to enable or disable specific warnings.
    • #pragma region / #pragma endregion: Used for grouping code in some IDEs, like Visual Studio.

    Summary of Preprocessor Directives

    Directive Purpose
    #include Includes a file (either standard library or user-defined) into the code.
    #define Defines a macro (constant or function-like) for substitution.
    #if Conditional compilation based on a condition.
    #ifdef Conditional compilation based on whether a macro is defined.
    #else, #elif Provides alternative conditions in a conditional compilation block.
    #error Causes a compilation error with a custom message.
    #pragma Provides compiler-specific instructions for special behaviors.

    Conclusion

    The C preprocessor is a powerful tool that allows you to manipulate your C code before it's compiled. With directives like #include, #define, and conditional compilation (#if, #ifdef), you can create flexible, efficient, and platform-specific code. The #error and #pragma directives provide more control over the compilation process, allowing you to catch issues early and optimize your code for different compilers.

    ← Previous topic 31
    File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    Next topic 33 →
    # and ## Operators, Predefined Symbolic Constants, Assertions

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.1kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals