문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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)

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.

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.

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.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top