Conditional Compilation In C: #ifndef #else #endif


In this video tutorial lets learn about preprocessor command or directives like #ifndef, #else and #endif. These directives are used for conditional compilation. #ifndef works completely opposite to #ifdef

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

How Does #ifndef Work?

The block of code between #ifndef and #endif works only if the macro name is NOT defined. If the macro name is defined, the compiler will skip the entire block of code inside #ifndef from compiling.

When To Use #ifndef

We’ve explained this in detail for video tutorial: Conditional Compilation In C: #ifdef #else #endif It holds good for this video tutorial too.

Video Tutorial: Conditional Compilation In C: #ifndef #else #endif


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

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

Source Code: Conditional Compilation In C: #ifndef #else #endif

#include<stdio.h>

#define iOS

int main()
{
    #ifndef iOS
        printf("I Love Apple Devices\n");
    #else
        printf("Code for Non Apple Devices\n");
    #endif // iOS

    return 0;
}

Output:
Code for Non Apple Devices

#include<stdio.h>


int main()
{
    #ifndef iOS
        printf("I Love Apple Devices\n");
    #else
        printf("Code for Non Apple Devices\n");
    #endif // iOS

    return 0;
}

Output:
I Love Apple Devices

In above programs, if iOS macro name is defined, then the set of code present inside #else block gets compiled and executed. If macro name iOS is not defined, then the code inside #ifndef block gets compiled and executed.

Note:

1. Using #else is optional. You can just use #ifndef and #endif.

2. Working of #ifndef is opposite to that of #ifdef.

3. This is similar to if else condition, but here the block of code which do not match the criteria doesn’t even get compiled. It’s treated like regular comments.

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

Leave a Reply

Your email address will not be published. Required fields are marked *