Home > Backend Development > C++ > Does `2[arr]` Work in C and C ?

Does `2[arr]` Work in C and C ?

DDD
Release: 2024-11-26 06:43:09
Original
500 people have browsed it

Does `2[arr]` Work in C and C  ?

Accessing Arrays Using Index[array] in C and C

Consider the following code snippet:

int arr[] = {1, 2, 3};
2[arr] = 5; // Does this compile?
assert(arr[2] == 5); // Does this assertion fail?
Copy after login

Some interviewers might ask why this code snippet compiles and executes without errors.

Understanding the Code

The expression 2[arr] is equivalent to *(2 arr). Since addition is commutative in C and C , the order of the arguments to [] does not matter. Therefore, 2[arr] effectively accesses the third element of the array arr.

Is This Guaranteed by the Language Specification?

Yes. The C and C standards explicitly state this behavior:

  • C99 Standard: Paragraph 6.5.2.1 states that E1[E2] is equivalent to *((E1) (E2)).
  • C 11 Standard: Paragraph 5.2.1.2 states that "E1[E2] is equivalent to "(*(E1) (E2))"

Therefore, accessing arrays using index[array] is guaranteed by the language specification, even if it seems unusual or counter-intuitive.

The above is the detailed content of Does `2[arr]` Work in C and C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template