Reputation: 458
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?
Upvotes: 3
Views: 293
Reputation: 72346
Strictly speaking, there are a number of evaluations going on in argv[1][2]
(which is equivalent to (argv[1])[2]
)
argv
1
2
argv[1]
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()
.
Upvotes: 10
Reputation: 234715
argv[1][2]
is grouped strictly as ((argv[1])[2])
.
So the expression is equivalent to *(*(argv + 1) + 2)
, which is a char
type.
Upvotes: 1
Reputation: 409176
For any array or pointer a
and index i
, the expression a[i]
is exactly equal to *(a + i)
. In short, all array indexing is "simple" pointer arithmetic.
For an array of arrays (or array of pointers) like argv
normally is, then argv[i][j]
is equal to (argv[i])[j]
which is equal to (*(argv + i))[j]
which is equal to (*(argv + i)) + j)
.
Upvotes: 2
Reputation: 18864
It's (argv[x])[y]
. If argv is and array of pointers to C
-strings (an argument to the main()
for instance). Then the first index picks the string and the second argument — a character in the string.
Upvotes: 1
Reputation: 13424
It is converted exactly to: *(*(argv + 1) + 2)
. You might want to learn about pointer arithmetic
Upvotes: 1