Home > Backend Development > C++ > Does 2[arr] = 5 Compile and Pass Assertion in C and C ?

Does 2[arr] = 5 Compile and Pass Assertion in C and C ?

Mary-Kate Olsen
Release: 2024-12-03 07:17:10
Original
256 people have browsed it

Does 2[arr] = 5 Compile and Pass Assertion in C and C  ?

Accessing Arrays by Index[array] in C and C

In a knowledge test sometimes posed by interviewers, the following code is presented:

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

It might initially appear that the expression 2[arr] should fail to compile, as it seems to be attempting to index an array using an integer as the array name. However, this unexpected syntax is indeed valid in both C and C .

To understand why, let's delve into the technicalities of the [] operator in these languages.

C and C Array Access Semantics

According to the C99 standard (6.5.2.1 paragraph 1), the [] operator expects arguments in the form:

  • One expression of pointer-to-object type
  • One expression of integer type
  • Resulting expression of the same type as the object

Further, paragraph 2 of the same section explains that E1[E2] is equivalent to (*((E1) (E2))). This indicates that the expression E1[E2] can be interpreted as a pointer manipulation:

  • E1 is converted to a pointer to the initial element of an array.
  • E2 is added to the pointer, resulting in a new pointer that points to the E2-th element of the array.
  • Dereferencing the resulting pointer returns the value of the selected array element.

Crucially, there is no requirement within the standard that the order of arguments to [] be sane. Therefore, the expression 2[arr] is treated as equivalent to (*((2) (arr))).

  • 2, an integer, is added to a pointer pointing to the first element of arr.
  • The resulting pointer points to the third element of arr.
  • Dereferencing the resulting pointer (i.e., accessing arr[2]) assigns the value 5 to the third element.

Therefore, both the assignment and the subsequent assertion succeed, as expected.

The above is the detailed content of Does 2[arr] = 5 Compile and Pass Assertion 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template