if 语句里面包含真和非真,但是如果我们没有写清楚真和非真的话,会如何呢?
if(x)
相当于
if(x != 0)
如果是指针的话,相当于
if(x != NULL)
而
if(1)
相当于
if(1 != 0)
还有
if(0)
相当于
if(0 != 0)
举个例子
#include<stdio.h>
int main()
{
int x = 2;
printf("x value:%d\n",x);
printf("code:'x==2'\nvalue:%d\n" ,x==2);
printf("code:'x!=2'\nvalue:%d\n" ,x!=2);
printf("code:'x=3'\nvalue:%d\n" ,x=3);
printf("code:'x-1'\nvalue:%d\n" ,x-1);
printf("code:'!x'\nvalue:%d\n" ,!x);
printf("code:'!1'\nvalue:%d\n" ,!1);
printf("code:'!0'\nvalue:%d\n" ,!0);
printf("code:'x'\nvalue:%d\n" ,x);
printf("\n");
if(0)
{
printf("if(0) is running!\n");
}
if(1)
{
printf("if(1) is running!\n");
}
if(x)
{
printf("if(x) is running!\n");
}
if(x = 0)
{
printf("if(x = 0) is running!\n");
}
if(x = 1)
{
printf("if(x = 1) is running!\n");
}
return 0;
}
输出结果
x value:2
code:'x==2'
value:1
code:'x!=2'
value:0
code:'x=3'
value:3
code:'x-1'
value:2
code:'!x'
value:0
code:'!1'
value:0
code:'!0'
value:1
code:'x'
value:3
if(1) is running!
if(x) is running!
if(x = 1) is running!