views:

137

answers:

4
+2  Q: 

AND/OR chains in C

I'm pretty much positive about this, but just to be on the safe side:

Does the C standard guarantee that AND chains (A && B && ...) will be evaluated left to right, and that evaluation will stop as soon as there's a 0?

Same question for OR. (As soon as there's a 1)

Can I count on this for other C-style languages?

Is this code safe:

if (somePtr!=NULL && somePtr->someMember==123)
{
     ...
}
+10  A: 

Yes, it is guaranteed for C, C++ and C#. The same goes for Delphi with "short curcuit evaluation" enabled.

This is behaviour numerous lines of code rely on to this moment.

sharptooth
Thanks everybody. Only one answer can be checked :P
+3  A: 

Yes, it is standardised by both C and C++.

anon
A: 

Yes, your assumptions about the order of operations in C are correct and the code snippet will work as intended. I would take other "C-style" languages on a case-by-case basis.

Judge Maygarden
A: 

Yes it does.

I have seen people who thought that was unclear, and replaced &&'s with this form:

if (a)
if (b)
if (c)
if (d) {
}

Personally I think that's kinda ugly.

T.E.D.