Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

Accessing arrays by index[array] in C and C++

There is this little trick question that some interviewers like to ask for whatever reason:

int arr[] = {1, 2, 3};
2[arr] = 5; // does this line compile?
assert(arr[2] == 5); // does this assertion fail?

From what I can understand, a[b] gets converted to *(a + b) and since addition is commutative, it doesn't really matter their order, so 2[a] is really *(2 + a) and that works fine.

Is this guaranteed to work by C and/or C++'s specs?

question from:https://stackoverflow.com/questions/5073350/accessing-arrays-by-indexarray-in-c-and-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes. 6.5.2.1 paragraph 1 (C99 standard) describes the arguments to the [] operator:

One of the expressions shall have type "pointer to object type", the other expression shall have integer type, and the result has type "type".

6.5.2.1 paragraph 2 (emphasis added):

A post?x expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

It says nothing requiring the order of the arguments to [] to be sane.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...