ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Preprocessor: #include, #define, Conditional Compilation, #error and #pragma
    Programming FundamentalsTopic 32 of 39

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

    7 minread
    1,146words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,146
      Code examples0
      DifficultyIntermediate