添加逻辑运算的结果是否定义了行为
is it defined behaviour to add the result of logical operation
是否可以(定义的行为)将逻辑运算的结果相加(因为它们应该只是 0
或 1
)?
如果我想计算大于零的数字,我可以这样做吗?(或者有更好的方法吗?)
int a[3] = {1,-5,3};
int result = 0;
for( int i = 0 ; i<3; i++)
{
result += a[i]>0;
}
引用 C11
,章节 §6.5.8,(强调我的)
Each of the operators <
(less than), >
(greater than), <=
(less than or equal to), and >=
(greater than or equal to) shall yield 1
if the specified relation is true and 0
if it is
false.107) The result has type int
.
那么你正在执行复合作业,其中要求
For the operators +=
and -=
only, either the left operand shall be an atomic, qualified, or
unqualified pointer to a complete object type, and the right shall have integer type; or the
left operand shall have atomic, qualified, or unqualified arithmetic type, and the right
shall have arithmetic type.
并且您的表达式满足约束条件。
所以是的,这是定义的行为。
也就是说,从语法的角度来看,您是安全的,因为默认的 operator precedence 符合您的期望。没有问题,但是明确(因此,确定)永远不会伤害。
您可以将表达式重写为
result += ( a[i] > 0 );
是否可以(定义的行为)将逻辑运算的结果相加(因为它们应该只是 0
或 1
)?
如果我想计算大于零的数字,我可以这样做吗?(或者有更好的方法吗?)
int a[3] = {1,-5,3};
int result = 0;
for( int i = 0 ; i<3; i++)
{
result += a[i]>0;
}
引用 C11
,章节 §6.5.8,(强调我的)
Each of the operators
<
(less than),>
(greater than),<=
(less than or equal to), and>=
(greater than or equal to) shall yield1
if the specified relation is true and0
if it is false.107) The result has typeint
.
那么你正在执行复合作业,其中要求
For the operators
+=
and-=
only, either the left operand shall be an atomic, qualified, or unqualified pointer to a complete object type, and the right shall have integer type; or the left operand shall have atomic, qualified, or unqualified arithmetic type, and the right shall have arithmetic type.
并且您的表达式满足约束条件。
所以是的,这是定义的行为。
也就是说,从语法的角度来看,您是安全的,因为默认的 operator precedence 符合您的期望。没有问题,但是明确(因此,确定)永远不会伤害。
您可以将表达式重写为
result += ( a[i] > 0 );