foo_l
foo_l

Reputation: 601

Conditional Compilation #ifdef

I am trying to understand the #ifdef macros. Sample code below.

getval(int val)
{
  if(val==0) {
    #ifndef PKT
    #define PKT
    #endif
  }
}
main() {
getval(0);
#ifdef PKT
printf("Packet\n");
#endif
}

I get output Packet even when I pass 1 to getval. Why am I getting output when PKT is not defined when val=1 ? Thanks.

Upvotes: 0

Views: 1396

Answers (4)

mohit
mohit

Reputation: 6074

This code could be used instead:

#define val 0

#if val==0
  #ifndef PKT
    #define PKT
  #endif
#endif //val == 0

int main()
{
#ifdef PKT 
    printf("Packet\n");
#endif
}

However, note that you've to define val before compilation.

Or, you could use enum:

typedef enum {PKT, NO_PKT} Packet;
Packet p;

getval(int val)
{
    if (val == 0)
    p = PKT;
    else
    p = NO_PKT;
}

int main()
{
   getval(1);
   if (p == PKT)
        printf("Packet\n");
}

Upvotes: 1

hivert
hivert

Reputation: 10667

#define and #ifdef are evaluated at compile time (actually even before compilation). They are evaluated on a text file, independently of the C code which is below. Therefore in

if(val==0) {
   #ifndef PKT
   #define PKT
   #endif
}

The #define is always done. Otherwise said, your code is equivalent to the same code where the define are outside a function. See https://en.wikipedia.org/wiki/C_preprocessor

Upvotes: 2

Oswald
Oswald

Reputation: 31685

That part where you #define PKT is evaluated by the preprocessor before the actual compilation, not during programm execution. Therefore, it is not subject to the condition if(val==0).

Upvotes: 2

phoxis
phoxis

Reputation: 61990

The # directives are compile time and not run time. So it doesn't matter what you pass. If the macro PKT is defined then "Packet" is printed, else not.

If you are running gcc you can do gcc -E myfile.c and check the result after preprocessing.

If you remove the bunch of preprocessor directives from your getval function, then the "Packet" will not be printed, because in that case PKT is not defined, and therefore the #ifdef PKT is false and the printf does not reach the compiler.

Upvotes: 2

Related Questions