Bob is right:Don wrote:Are you sure about that? I'm pretty sure it is implementation defined unless that has changed.bob wrote:Last time I looked, ansi standards said 0 or 1 for that. The test for true will take any non-zero value for true, but a == b is supposed to return 0 or one only, so far as I know. Other languages are different (Fortran used to use -1 for true on many machines, as one example).michiguel wrote:The second one is incorrect and it is not guaranteed to give you what you expect. (a==b) could give you any number as long as is not zero! Even if it does, it hurts readability.metax wrote:Is there any difference in the performance of the following two lines:
1. if (a == b) c++;
or
c += (a == b);
Is any of these faster?
Stay away from it!
Miguel
The current, amended C standard says:
ISO/IEC 9899:TC3 Committee Draft — Septermber 7, 2007 WG14/N1256
6.5.9 Equality operators
Syntax
1 equality-expression:
relational-expression
equality-expression == relational-expression
equality-expression != relational-expression
Constraints
2 One of the following shall hold:
— both operands have arithmetic type;
— both operands are pointers to qualified or unqualified versions of compatible types;
— one operand is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void; or
— one operand is a pointer and the other is a null pointer constant.
Semantics
3 The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence.93) Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int. For any pair of operands, exactly one of the relations is true.
4 If both of the operands have arithmetic type, the usual arithmetic conversions are performed. Values of complex types are equal if and only if both their real parts are equal and also their imaginary parts are equal. Any two values of arithmetic types from different type domains are equal if and only if the results of their conversions to the (complex) result type determined by the usual arithmetic conversions are equal.
Footnote 93) Because of the precedences, a<b == c<d is 1 whenever a<b and c<d have the same truth-value.
In C++, the result is boolean rather than integral.