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());
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.
Yes. && and || short circuit in C and C++; it is guaranteed by the standard.
See also: Is short-circuiting logical operators mandated? And evaluation order?
精彩评论