int*类型变量a的&a[i]与a+i是否存在执行逻辑差异?
&a[i]与a+i执行逻辑的差异解析 Great question! Let's break this down clearly—even though both expressions end up returning the same int* pointer, their underlying execution steps do differ, just like you suspected.
先看a+i的执行逻辑
When you write a+i, here's exactly what happens:
- First, the array name
ais implicitly converted to a pointer pointing to the first element of the array (soabecomes equivalent to&a[0], typeint*). - Then, we perform pointer arithmetic: adding
ito this pointer shifts it forward byi * sizeof(int)bytes, directly landing on the address of the i-th element in the array.
This is a tight, single-operation chain—only pointer conversion plus addition, no extra steps.
再拆解&a[i]的执行逻辑
&a[i] looks like one expression, but it's actually two distinct operations working in sequence:
- The subscript operator
a[i]is defined by the C/C++ standard as equivalent to*(a+i). So first, we do the same pointer arithmetic as above to get the pointer to the i-th element, then dereference it to access the value ofa[i]. - Next, we apply the address-of operator
&to that dereferenced value, which gives us back the address of the i-th element.
Wait a second—does that mean we're wasting cycles dereferencing just to take the address again? Don't worry, modern compilers are smart enough to optimize this away. They recognize that &*(a+i) is exactly the same as a+i, so they'll generate identical machine code for both expressions. But syntactically and conceptually, &a[i] does involve two separate operators, while a+i uses only one.
关键总结
- Conceptually:
a+iis a direct pointer arithmetic operation;&a[i]is a combination of subscript access (pointer arithmetic + dereference) and address-of. - Practically: Compilers optimize
&a[i]toa+i, so there's no performance difference between the two. - Result: Both expressions always evaluate to the same
int*pointer pointing to the i-th element of the array.
内容的提问来源于stack exchange,提问作者Joxon

