0

I have this code but not able to understand the output. Can someone help out to know the behaviour

#include<stdio.h>
int main(){

int a =1;
#if(a==0)
  printf("equal");
#else if
  printf("unequal");
#endif

return -1;
}

Output comes out to be equal. Strange for me.

Also if i change the if condition to a==2, the output comes unequal

If i try to print value of 'a' inside 'if' block something like

#if(a==0)
 printf("value of a: %d",a);

output comes out to be value of a: 1

Please some one explain the output.

1
  • Are you aware what the C preprocessor is and how it functions? I recommend Kernighan, Ritchie, The C Programming Language, 2nd ed as required reading for any prospective C programmer. Commented Jun 19, 2013 at 19:03

3 Answers 3

6

The a in the preprocessor directive refers to preprocessor definitions, not variables in your program. Since a is not #defined, its value is effectively 0 for the purposes of #if.

Sign up to request clarification or add additional context in comments.

Comments

3

The preprocessor directives (the lines starting with #) are dealt with at compile time, not at runtime. The a in that #if is not the same as the a variable you declared. The preprocessor just replaces it with 0, since there is no #define a statement anywhere. The variable a is unused in your program. If you do use it, like in the printf statement you show, it will get printed as expected - a value of 1 that you assigned to it.

Comments

3
#include<stdio.h>
int main(){

int a =1;
#if(a==0)
  printf("equal");
#else if
  printf("unequal");
#endif

return -1;
}

which you pass to the compiler will first go through the preprocessor whose output is then sent as an input to the compiler; the preprocessor will send

#include<stdio.h>
int main(){

int a =1;
printf("equal");

return -1;
}

to the compiler, which is the reason you see equal always. The reason is since a as a macro is undefined, the first condition is true, there by leading to only passing that statement on to the compiler. If you try adding #define a 1 next to the include directive, then you'll always see unequal as an output; but these changes affect only the compile time macro a and not the runtime variable a (both are entirely different).

All this because preprocessor is concerned only with compile-time constructs. What you really need may be

#include<stdio.h>
int main(){

   int a =1;
   if(a == 0)
     printf("equal");
   else
     printf("unequal");

   return 0;
}

Aside: Return 0 when you're program is successful, returning negative values from main usually means some error state termination of your program.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.