Re: Unnecessary Boolean Warning
Re: Unnecessary Boolean Warning
- Subject: Re: Unnecessary Boolean Warning
- From: Greg Parker <email@hidden>
- Date: Wed, 3 Aug 2011 18:19:07 -0700
On Aug 3, 2011, at 5:56 PM, Graham Cox wrote:
> On 04/08/2011, at 1:52 AM, Jean-Daniel Dupas wrote:
>> One important difference for instance is that if you write if (a() & b()), both a() and b() will always be executed, while if you write if (a() && b()), b() will be executed only if a() is true.
>
> The C language doesn't make any guarantees about that. While this optimisation is to be expected, the order of execution (left to right) and the optimisation (b not executed) is implementation dependent.
>
> This is a classic question for coding job interviews.
Incorrect. The C language guarantees short-circuit evaluation for '&&'. The left side is evaluated first. If it is false, then the right side is not evaluated. '||' and '?:' similarly guarantee short-circuit evaluation.
You're correct for all other operators. '&' does not guarantee short-circuit evaluation or any particular order of execution.
C99 6.5.13.4 (Logical AND operator)
"Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares equal to 0, the second operand is not evaluated."
C99 6.5.14.4 (Logical OR operator)
"Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated."
C99 6.5.15.4 (Conditional operator)
"The first operand is evaluated; there is a sequence point after its evaluation. The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated), converted to the type described below.95) If an attempt is made to modify the result of a conditional operator or to access it after the next sequence point, the behavior is undefined."
--
Greg Parker email@hidden Runtime Wrangler
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden