0

我有这段代码,但无法理解输出。有人可以帮助了解行为吗

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

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

return -1;
}

输出结果是equal。对我来说很奇怪。

另外,如果我将if条件更改为a==2,则输出来unequal

如果我尝试在“if”块中打印“a”的值,例如

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

输出结果是value of a: 1

请有人解释输出。

4

3 回答 3

6

a处理器指令中的 是指预处理器定义,而不是程序中的变量。由于a不是#defined,因此它的值有效地0用于#if.

于 2013-06-19T17:49:14.710 回答
3

预处理器指令(以 开头的行#)在编译时处理,而不是在运行时处理。ain 那与#ifa声明的变量不同。预处理器只是将其替换为0,因为任何地方都没有#define a声明。该变量a在您的程序中未使用。如果您确实使用它,就像在printf您显示的语句中一样,它将按预期打印 -1您分配给它的值。

于 2013-06-19T17:49:25.527 回答
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.

于 2013-06-19T17:54:07.137 回答