C Programming - C Preprocessor - Discussion

5. 

Will the program compile successfully?

#include<stdio.h>

int main()
{
    #ifdef NOTE
        int a;
        a=10;
    #else
        int a;
        a=20;
    #endif
    printf("%d\n", a);
    return 0;
}

[A]. Yes
[B]. No

Answer: Option A

Explanation:

Yes, this program will compile and run successfully and prints 20.

The macro #ifdef NOTE evaluates the given expression to 1. If satisfied it executes the #ifdef block statements. Here #ifdef condition fails because the Macro NOTE is nowhere declared.

Hence the #else block gets executed, the variable a is declared and assigned a value of 20.

printf("%d\n", a); It prints the value of variable a 20.


Sonalia said: (Dec 30, 2011)  
Can anyone explain in details?

Sandeep Barnwal said: (May 24, 2014)  
Yes, #ifdef NOTE is true if NOTE is defined as macro somewhere in program. Here, NOTE is not defined anywhere so, #ifdef returns false and else statement gets executed.

Hence, 20 will be printed.

#include<stdio.h>
#define Note 1
int main()
{
#ifdef NOTE
int a;
a=10;
#else
int a;
a=20;
#endif
printf("%d\n", a);
return 0;
}

As we can see macro foe NOTE is defined, #ifdef will return true and 10 will be output.

#ifdef only looks for the macro definition.
:)

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.