Reputation: 2080
Is it okay (defined behavior) to add up the result of logical operations (as they should just be 0
or 1
)?
Can I do something like this if I want to count the numbers bigger than zero?(or is there a better way?)
int a[3] = {1,-5,3};
int result = 0;
for( int i = 0 ; i<3; i++)
{
result += a[i]>0;
}
Upvotes: 3
Views: 74
Reputation: 134346
Quoting C11
, chapter §6.5.8, (emphasis mine)
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
.
Then you're performing a compound assignment, where it is required that
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.
and your expression satisfies the constraint.
So yes, it is defined behaviour.
That said, from a syntax perspective, you're only safe because of the default operator precedence matches your expectation. There's no problem as such, but being explicit (and thus, sure) never hurts.
You can rewrite the expression as
result += ( a[i] > 0 );
Upvotes: 5