views:

198

answers:

6

Hi guys, my question is essentially in the title. Basically I've learned that in Java the && operator acts like a short circuit, so that if the first condition evaluates to false it doesn't look at the rest of the statement. I assumed this was the case in c++ but I'm writing a bit of code which first checks that an index has not exceeded a list size, then compares that index in the list to another number. Something like:

//let's say list.size()=4;

for(int i=0; i<10; i++)
{
   if(i < list.size() && list.get(i) == 5)
       //do something
   ...
}

That's not the exact code but it illustrates the point. I assume that since i > the list size the second half won't get evaluated. But it appears that it still does, and I believe this is causing a Seg Fault. I know I can use nested ifs but that's such an eyesore and a waste of space. Any help?

+2  A: 

C++ && and || operators do shortcircuiting too. Be careful, maybe you put a single & and C++ is using tbe binary and operator, which is not shortcircuited. Post more relevant code if you need more help.

jbernadas
+1  A: 

C++ short circuits && and || just like Java. in if(i < list.size() && list.get(i)) , list.get(i) will not be evaluated if i < list.size() is false.

nos
+6  A: 

Yes, in C and C++ the && and || operators short-circuit.

Blastfurnace
+5  A: 

Shortcutting works the same in C, C++, and Java.

However, given the example code, you may get a segfault if list is null. C++ has no equivalent to Java's NullPointerException. If list might be null, you need to test for that as well.

Updated The latter half of that only applies if list is a pointer. (Which is does not appear to be.) If that was the case it would look like:

if (list && i < list->size() && list->get(i) == 5)
Devon_C_Miller
I didn't know you could test for something being null that way. Thanks for the info.
Mark Peters
Based on the usage of `list.size()`, it appears that `list` is not a pointer in this case, so testing for null won't work.
GBegen
@GBegen Good catch. Can't believe I missed that. I know I've been solidly in Java lad for months now, but... wow. Go me.
Devon_C_Miller
+6  A: 

Yes && behaves similarly in Java as in C++. It is a short circuiting operator and also a sequence point [in C++]. The order of evaluation of operands is well defined i.e from left to right.

Prasoon Saurav
A: 

The && and || operators short-circuit if not overloaded. I believe they can be overloaded, however, in which case they would not short-circuit if used on types for which an overload was in effect.

supercat