mr_azad mr_azad - 1 month ago 7
C++ Question

Confusion with #ifndef and #ifdef

#include <iostream>
using namespace std;

#ifndef R
#define N1 10

#ifndef R
#define N2 11
#endif


#endif

int main(){
cout << N2 << endl;
}


From my understanding if
R
is not defined then
N1
will be 10.

And second case where again
R
is defined again it should not be able to define
N2
as 11, because
R
is already defined. I am just confused about it, And one Can please help to understand the point I have missed.

Answer

Let's walk through the code:

#ifndef R

R hasn't been defined yet, so step into the branch:

   #define N1 10

N1 becomes 10

   #ifndef R

R still hasn't been defined yet, so step into nested branch

      #define N2 11

N2 is assigned to 11

   #endif

Ends the nested branch

#endif

Ends the primary branch

So in the end R was never defined, so we assign N2 successfully.

You need to explicitly #define R or use -DR in the compiler line to define R, it won't get defined for you within a ifndef R branch.

Comments