Conditional Compilation In C: #if #elif #else #endif

In this video tutorial lets learn about preprocessor command or directives like #if, #elif, #else and #endif. These directives are used in conditional compilation.

Related Read:
Logical Operators In C
Conditional Compilation In C: #ifdef #else #endif

How Does #if and #elif Work?

The block of code inside #if block works only if the condition or the expression in resolved to non-zero number. If the expression is resolved to zero, then the code inside #if is skipped from compilation.

Same is true for #elif: If the condition or the expression is resolved to 0 then the code inside #elif block is skipped from compilation. If it’s resolved to non-zero number then the block of code inside #elif gets compiled and executed.

#else is optional and when used, it should be present only once between #if and #endif, and it should be present at the end(just before the #endif directive). If none of the conditions in #if and #elif match, then the code inside #else directive block gets executed.

#elif is also optional. But it can be used any number of times inside #if and #endif. But it should always be written after #if and not before it. It should be present before #else and not after #else directive.

Note: We can have nested #if #elif #else #endif inside #if and/or #elif and/or #else block. Nesting can go any number or depth.
But remember to have #endif for every #if.

Video Tutorial: Conditional Compilation In C: #if #elif #else #endif


[youtube https://www.youtube.com/watch?v=0s-y4WADkf0]

YouTube Link: https://www.youtube.com/watch?v=0s-y4WADkf0 [Watch the Video In Full Screen.]

When To Use #if, #elif, #else and #endif?

1. When you want certain code to be skipped: #if or #elif or #else part of the code is compiled and executed only when the conditions are met.

2. To write portable code: Again, like that of in #ifdef and #else, we could write portable code. That is, we can write code for specific devices in #if, #elif and #else part and the compiler compiles the code specific to that device. All other code will be treated as comments.

3. Saving memory and file size: We could use it in big projects. We could include device specific files inside #if, #elif and #else blocks depending upon the condition. This way we could avoid including or importing all the files into our source code.

#include<stdio.h>

int main()
{
    #if MARKS
        printf("GRADE A\n");
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
Your Result

Here macro template is not even defined. And for #if to resolve and print the code inside its block, MARKS should be evaluated to non-zero number.

#include<stdio.h>

#define MARKS

int main()
{
    #if MARKS
        printf("GRADE A\n");
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
Your Result

Here even though MARKS is defined, it doesn’t have a non-zero value, so the code inside #if block isn’t compiled.

#include<stdio.h>

#define MARKS 50

int main()
{
    #if MARKS
        printf("GRADE A\n");
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
GRADE A
Your Result

Here MARKS has a macro expansion as 50, which not zero, so code inside #if gets compiled and executed.

Using logical operatation

#include<stdio.h>

#define MARKS 50

int main()
{
    #if(MARKS <= 100 && MARKS >= 80)
        printf("GRADE A\n");
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
GRADE A
Your Result

Check the condition for #if. We can use logical operator and/or arithmetic operators and/or relational operators and/or Conditional Operators in the condition.

Nesting of Directives

#include<stdio.h>

#define MARKS 50

int main()
{
    #if(MARKS <= 100)
        printf("GRADE A\n");
        #if(MARKS >= 80)
            printf("You're excellent!\n");
        #else
            printf("You're not that excellent yet!\n");
        #endif
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
GRADE A
You’re not that excellent yet!
Your Result

We can nest any number of #if #endif and/or #if #else #endif and/or #if #elif #endif and/or #if #elif #else #endif inside #if and/or #elif and/or #else.

Source Code: Conditional Compilation In C: #if #elif #else #endif

#include<stdio.h>

#define MARKS 50

int main()
{
    #if(MARKS <= 100 && MARKS >= 80)
        printf("GRADE A\n");
    #elif(MARKS <= 79 && MARKS >= 60)
        printf("GRADE B\n");
    #elif(MARKS <= 59 && MARKS >= 40)
        printf("GRADE C\n");
    #elif(MARKS <= 39 && MARKS >= 30)
        printf("GRADE D\n");
    #else
        printf("Please retake the test!\n");
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
GRADE C
Your Result

Only 1 block of code is compiled and executed here, even if multiple conditions are satisfying. Whichever condition returns non-zero number first, the code inside its block gets executed. All other code will be skipped.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

include directive in C Program

Usually you can see these “include” directive at the very top of your source code. It’s called a preprocessor directive.

All preprocessor statements in C start with a hash(#) symbol. include directive is similar to imports statement in Java.

 
#include < stdio.h >
int main()
{
    printf("Microsoft\n Apple\n Oracle\n Google\n Yahoo\n");
    return 0;
}

Output:
Microsoft
Apple
Oracle
Google
Yahoo

include Preprocessor Directive In C Program


[youtube https://www.youtube.com/watch?v=4BBml3T8WK4]

YouTube Link: https://www.youtube.com/watch?v=4BBml3T8WK4 [Watch the Video In Full Screen.]


This “include” directive causes one file to be included in another. For example, when we include stdio.h (header file) in our above program, all the content(code) gets imported or included in our program source code. This way we can make use of any function present inside stdio.h library file in our c program.

Car Program

We are writing Car simulation program in C – we write all the related code in different files by group them together and then include it in our main Car program. For example, we can separate wheels, color and display related things and then include all those things in our main Car program. This way our main Car program source code looks less clumsy and more over we need not worry about the implementation details present in those files.

Ex: When we include stdio.h file, we do not worry about the implementation details of printf() method. We simply use it for displaying content to the console. All the implementation details are present in stdio.h header file.

There are 2 ways of including header files

 
#include < stdio.h >

#include "Mylib.h"

When we use < and > to wrap around the file name, the linker looks for the files in standard library storage folder. When we wrap the file name in double quotes it looks for the file in current directory.

Usually user written, custom header files are wrapped in double quotes.

We’ll be writing our own library files in this video series. But for now it’ll get too complicated if we go any further.

Note: There are many preprocessor statements other than include directive. We’ll discuss them as and when we use it in our C programs.

Structure of a basic C Program

Lets write our first C program – the typical “Hello World!” program.

In this video tutorial lets learn the structure of a basic C program:
1. Preprocessors – include directive.
2. Main method/function.
3. printf method/function.
4. Semicolon syntax.
5. Indentation for readability of code.

Source Code: A Simple C Program

#include<stdio.h>

int main()
{
    printf("Microsoft\n Apple\n Oracle\n Google\n Yahoo\n");
    return 0;
}

Output:
Microsoft
Apple
Oracle
Google
Yahoo

Structure of a basic C Program


[youtube https://www.youtube.com/watch?v=3Yu6u3tmBS4]

YouTube Link: https://www.youtube.com/watch?v=3Yu6u3tmBS4 [Watch the Video In Full Screen.]


Preprocessor statement

The “include” directive which we see in the first line is a preprocessor directive. Here we are including a standard library file which has some set of useful functions in it, which we are using in our “Hello World” C Program.

stdio stands for “Standard Input Output”. As the name suggests this library file has functions to read and write data to console window, along with other many useful functions. For example, printf() is a function present in stdio.h library file. We simply use it in our program to print data on to the console window. We need not know the implementation details of printf method/function.

main() method

Main method or function is part of all ‘C’ programs. It’s entry point of any C program execution. Function is a way of grouping some code together. We can write any logic/statements inside a function.

It’s a standard that main always returns a integer value. Thus main is preceded by a keyword called int, which means integer. It’s a keyword or reserve word. We’ll know more about keywords(or reserve words) in a separate video tutorial. Since main method needs to return a integer value, we explicitly return 0 at the end.

Readability of code

It’s very important that we write code which is readable. It helps in maintaining the code. Large programs get too clumsy very easily and reading and understanding code often becomes difficult. So we need to indent the code and make sure its readable as far as possible.

Note:
Main method/function doesn’t take any argument.