1

I have seen a particular style of code that according to me is dangerous and should be avoided, but I have seen it so many times in lot of places, that I am confused whether or not I am missing something.

int a[100];

/* Some code later */

for(i =0; (i < 100 && a[i] != 0); i++)
           :
           :

In the above code it is possible that the expression (i < 100 && a[i] != 0) is evaluated from right to left, in that case when i == 100, we are going out of bounds of the array 'a'.

Can someone explain whether or not this is safe code

Pratt
  • 851
  • 2
  • 10
  • 16

5 Answers5

4
  1. The order of evaluation or arguments is well defined for &&, it cannot be changed.
  2. #1 coupled with short circuiting makes this perfectly safe.

References:

C++03 Standard:

Section 5: Expressions, Para 4:

except where noted [e.g. special rules for && and ||], the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is Unspecified.

C99 Standard:

Section 6.5:

The grouping of operators and operands is indicated by the syntax.72) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.

Note: Emphasis mine.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
3

I think you can count on short-circuit evaluation not to access a[i] when i < 100 is false.

Brian Cain
  • 14,403
  • 3
  • 50
  • 88
2

It is not possible that (i < 100 && a[i] != 0) is evaluated from right to left. && and || are explicitly defined as evaluating their left argument first, and their right argument only if necessary.

rici
  • 234,347
  • 28
  • 237
  • 341
1

"In the above code it is possible that the expression (i < 100 && a[i] != 0) is evaluated from right to left..."

No, it is not possible, neither in C nor in C++. In both languages this expression is guaranteed to be evaluated from left to right. And if the first part is false, the second part is guaranteed not to be evaluated.

So, the code is perfectly safe from out-of-bounds access.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

&& and || are evaluated left to right as every one said. You might want to consider following link for further information

http://en.cppreference.com/w/cpp/language/operator_precedence

SureshS
  • 589
  • 8
  • 23