c++中if(1)是什么意思,为什么if()里面不是一个表达式,如知道请详细解释

如题所述

在C++里0表式假,非0表式真
1就是真了
if里的表达式也是用真假来判断是不是满足if条件
if(1)这里1就是表达式,是一个永远为真的表达式
这个if一直都会执行的
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-10-11
if是个判断语句
相应的可以使用else
if里面是一个判断语句,如果里面是一个数字,判断其是不是为0,若为0,则不执行if下面的一条语句,或者执行else。如果不是0,则执行if下面的语句,并且不执行else。
另外还有if里面是true,null等情况比较多。我发个msdn解释给你。

if, else Statements
if( expression )
statement1
[else
statement2]

The if keyword executes statement1 if expression is true (nonzero); if else is present and expression is false (zero), it executes statement2. After executing statement1 or statement2, control passes to the next statement.

For related information, see switch.

Example 1

if ( i > 0 )
y = x / i;
else
{
x = i;
y = f( x );
}
In this example, the statement y = x/i; is executed if i is greater than 0. If i is less than or equal to 0, i is assigned to x and f( x ) is assigned to y. Note that the statement forming the if clause ends with a semicolon.

When nesting if statements and else clauses, use braces to group the statements and clauses into compound statements that clarify your intent. If no braces are present, the compiler resolves ambiguities by associating each else with the closest if that lacks an else.

Example 2

if ( i > 0 ) /* Without braces */
if ( j > i )
x = j;
else
x = i;
The else clause is associated with the inner if statement in this example. If i is less than or equal to 0, no value is assigned to x.

Example 3

if ( i > 0 )
{ /* With braces */
if ( j > i )
x = j;
}
else
x = i;
The braces surrounding the inner if statement in this example make the else clause part of the outer if statement. If i is less than or equal to 0, i is assigned to x.
第2个回答  2010-10-11
if()里面没有规定是一个表达式哦,而是要求是个布尔值
表达式的效果也是给if返回一个布尔值,真或者假
这里的1可以自动转换的,c++对int形式的转换好像是“非0的转为布尔值1,也就是真;0转换为布尔值0,也就是假”
第3个回答  2010-10-11
if()中的是一个bool型
bool型可以取值True 和False
其中在计算机中可用1代替True 0代替False
因此如果括号中表达式的计算结果是非零的 就默认等同于1(True)

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网