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.
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.
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.
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.
The logical OR operator also performs short-circuit evaluation: if the left-hand operand is true, the right-hand expression is not evaluated.
Yes, you can rely on the builtin operator &&
to short-circuit. That's part of its specification.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With