Does && in C ++ behave the same as && in Java?

my question is essentially in the title. I basically found out that in Java &&, an operator acts like a short circuit, so if the first condition evaluates to false, it doesn't consider the rest of the statement. I assumed it was in C ++, but I write some code that first checks that the index has not exceeded the size of the list, and then compares this index in the list with a different number. Sort of:

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

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

This is not exact code, but it illustrates the point. I assume that since i> is the size of the list, the second half will not be evaluated. But it looks like this is still happening, and I believe that it causes Seg Fault. I know that I can use nested ifs, but it is such an eyesore and a waste of space. Any help?

+3
source share
6 answers

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

+6
source

The shortcut works the same in C, C ++, and Java.

However, given the example code, you can get segfault if listis null. C ++ has no Java NullPointerException equivalent. If the list can be null, you also need to check it.

Update The last half of this applies only if the list is a pointer. (It doesn’t look like it.) If it were, it would look like this:

if (list && i < list->size() && list->get(i) == 5)
+5
source

&& Java, ++. , [ ++]. i.e .

+3

++ && || . , , , ++ , . , .

+2

++ && & || Java. if(i < list.size() && list.get(i)), list.get(i) , i < list.size() .

+1

& & || , . , , , , .

+1

Source: https://habr.com/ru/post/1768087/


All Articles