tags:

views:

244

answers:

2

In Java, I use

if (a != null && a.fun());

by taking full advantage of short-circuit evaluation and expression are evaluated from left to right?

In C++, can I do the same? Are they guarantee to portable across different platform and compiler?

if (a != 0 && a->fun());
+5  A: 

Yes. && and || short circuit in C and C++; it is guaranteed by the standard.

See also: http://stackoverflow.com/questions/628526/is-short-circuiting-boolean-operators-mandated-in-c-c-and-evaluation-order

Crashworks
+9  A: 

Yes, it is guaranteed for the "built in" types. However, if you overload && or || for your own types, short-circuited evaluation is NOT performed. For this reason, overloading these operators is considered to be a bad thing.

anon
This is to my knowledge the exact reason operator overloading is not in Java.
Thorbjørn Ravn Andersen
@Thorbjørn: could be true, but sounds mad to me - Java could have allowed operator overloading but not permitted overloads of those two operators (or the ternary ?: operator, which C++ doesn't overload either). I always assumed it was because of the "code that looks local should be local" argument, that anything which calls user-defined code should "look like" it calls out of line, with an explicit method call.
Steve Jessop
Madness is in the eye of the beholder. Overloading has some very distinct disadvantages, namely that you cannot trust ANYTHING to have the behaviour you expect, is enough for me to think Java got this right.
Thorbjørn Ravn Andersen
I'm not saying it's mad to forbid operator overloading. I'm saying it's mad to forbid it for that reason, which is both easily overcome, and far less significant than other plausible reasons. It's an exaggeration to say that in C++ you cannot trust anything - you do have to be cautious in what you expect, though. Most of the things which in C++ are "unpredictable" by Java programmers wouldn't even compile in Java or C in the first place. Assignment/conversion are the truly awkward ones. I've never shared the panic on seeing two objects added together, but I appreciate that it's not mad.
Steve Jessop