[英]what does if(i-2) mean in C language?
So,I understand everything in code except this if
statement - if(i-2)
: 所以,我理解代码中除了
if
语句之外的所有内容-if if(i-2)
:
for (i = -1, j = 0; i < 4; i++, j++)
if (i - 2)
printf("%d\t", j * (i + 2));
Can anyone explain meaning of this if
statement,does it have any influence on printf
? 谁能解释这个
if
语句的含义,它对printf
有影响吗? Thanks. 谢谢。
The statement under an if
is executed if the controlling expression is true. 下一个声明
if
如果控制表达式为true时执行。 In C, an expression that evaluates to 0 is considered false, while any other value is considered true. 在C语言中,计算结果为0的表达式被视为false,而其他任何值均被视为true。
So if (i-2)
means the printf
will get executed if i-2
is non-zero, ie when i
is not equal to 2. 因此,
if (i-2)
表示如果i-2
不为零,即当i
不等于2时, printf
将被执行。
In C, an integer is treated like a boolean in an if
statement: 在C语言中,
if
在if
语句中将整数视为布尔值:
So if (i-2)
is equivalent to if (i != 2)
. 所以
if (i-2)
等于if (i != 2)
。
In c any value can be used in an if
statement not just boolean expressions. 在c语言中,可以在
if
语句中使用任何值,而不仅仅是布尔表达式。 This devolves into expression != 0. Often this is against style guides as it can be confusing and error prone. 它演变为表达式!=0。通常这与样式指南背道而驰,因为它可能会造成混淆并且容易出错。
The two following are equivalent 以下两个是等效的
if (val) ...
if (val != 0) ...
So in you're case 所以在你的情况下
if (i - 2)
will be true for every value of i
except 2
when i-2
is 0
当
i-2
为0
时,除2
以外的所有i
值都为true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.