Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I rely on short-circuit evaluation to check vector bounds in C++?

Tags:

c++

stl

Is the following code acceptable?

if(vector.size() > 0 && vector[0] == 3) {
}

Or is there a chance that it will crash when the vector is empty? I haven't noticed this happening, but I'm worried that it's still possible.

like image 942
mimicocotopus Avatar asked Dec 20 '12 21:12

mimicocotopus


People also ask

Does C use short-circuit evaluation?

In imperative language terms (notably C and C++), where side effects are important, short-circuit operators introduce a sequence point – they completely evaluate the first argument, including any side effects, before (optionally) processing the second argument.

What is the drawback of short-circuit evaluation method?

Disadvantage 1: Any logic which was expected to be executed as part of the conditions which are bypassed will not be executed. I.e. say we have Condition-1 OR Condition-2 where condition-1 is evaluated to TRUE.

What are the advantages about short-circuit evaluation?

The advantages of C#'s short-circuit evaluation. There are two benefits to the short-circuit behaviour of the && and || operators. It makes our true/false conditions more efficient since not every expression has to be evaluated. And short-circuiting can even prevent errors because it skips part of the code.

Which of the following operators can be used to do a short-circuit evaluation?

The logical OR operator also performs short-circuit evaluation: if the left-hand operand is true, the right-hand expression is not evaluated.


2 Answers

Yes, you can rely on the builtin operator && to short-circuit. That's part of its specification.

like image 80
Pete Becker Avatar answered Oct 16 '22 15:10

Pete Becker


Yes, that works, but it would be more idiomatic to say !vector.empty() && vector[0] == 3: That will work for all containers with maximal efficiency, so it's never worse, sometimes better and always more readable.

like image 38
Kerrek SB Avatar answered Oct 16 '22 15:10

Kerrek SB