Code Yarns โ€๐Ÿ‘จโ€๐Ÿ’ป
Tech Blog โ– Personal Blog

Array subscript versus arithmetic in C++

๐Ÿ“… 2020-Jun-30 โฌฉ โœ๏ธ Ashwin Nanjappa โฌฉ ๐Ÿ“š Archive

In C++, given a pointer (or iterator) a and integer i, which of these two expressions should you prefer to use: a + i or &a[i]?

These two expressions are equivalent and legal, as long as a + i points to a valid element of the underlying array.

The a + i expression has two advantages compared to &a[i]:

Both of the above subtle differences are listed in the C++20 standard ยง7.6.6 Additive operators:

When an expression J that has integral type is added to or subtracted from an expression P of pointer type, the result has the type of P. (4.1) โ€” If P evaluates to a null pointer value and J evaluates to 0, the result is a null pointer value. (4.2) โ€” Otherwise, if P points to an array element i of an array object x with n elements, the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) array element i + j of x if 0 โ‰ค i + j โ‰ค n and the expression P - J points to the (possibly-hypothetical) array element i โˆ’ j of x if 0 โ‰ค i โˆ’ j โ‰ค n.