C++ index evaluation direction

  • A+
Category:Languages

Consider the following code: argv[1][2]

How does C++ handle the index evaluation? For example left to right: [1] is evaluated before [2], right to left: [2] is evaluated before [1] or does this depend on the compiler used?

 


Strictly speaking, there are a number of evaluations going on in argv[1][2] (which is equivalent to (argv[1])[2])

  1. Evaluate argv
  2. Evaluate 1
  3. Evaluate 2
  4. Evaluate argv[1]
  5. Evaluate argv[1][2]

An operator expression can't really be evaluated without knowing what its operands' values are, so #1 and #2 must happen before #4, and #3 and #4 must happen before #5.

Of course, "evaluate 1" doesn't have much meaning since it's just a literal known value. But if the expression were something like argv[f1()][f2()] instead, then the order of subexpression evaluations can matter.

In versions of C++ up to C++14, it is unspecified in argv[f1()][f2()] whether f1() or f2() is called first. C++17 introduced a lot of additional guarantees on the order of subexpressions, including a rule for array subscripting: in A[B], all evaluations and side effects for subexpression A now happen before all evaluations and side effects of subexpression B. So C++17 guarantees in this case that f1() will be called before f2().

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: