-1

What I know?

There is an array, int a[10], and to access first element of it, I can either use a[0] or 0[a]; which leads to

*(a+0) and *(0+a) -> Both results in accessing first element of the array. 

What I want to know?

I want to know whether are any cases where it is more practical to use 0[a] instead of a[0]?

Johan Råde
  • 20,480
  • 21
  • 73
  • 110
Whoami
  • 13,930
  • 19
  • 84
  • 140

3 Answers3

2

No, it's the other way around. a + b and b + a mean the same thing when one is a pointer and the other is an integer. That leads to *(a + b) and *(b + a) meaning the same thing, and that leads to a[b] and b[a] meaning the same thing.

There are some cases that are made more readable by adding a pointer to an integer (i + p). There are no cases that are more readable by indexing an integer (i[p]). Don't do it.

1

In your example int a[10] no, it is never more practical to write 0[a].

FredOverflow links to an example, but it's a bit of a struggle to extract the reason from the comments. So I'll add it as an answer.

a[0] and 0[a] are not necessarily equivalent if a can be any expression (or for example a macro argument) rather than a simple name.

Suppose a expands to b + 1. Then b + 1[0] is not at all the same thing as 0[b + 1].

To cover this awkward case, you could ask whether it's more practical to use 0[a] instead of (a)[0]. To which the answers is still no. Unless maybe you favour brevity over familiarity.

A macro can expand to contain un-matched brackets, like #define a x]+0[x or something, so the two still aren't strictly equivalent in all cases. But if a is an expression then 0[a] and (a)[0] are equivalent.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
-5

(0+a) This mean the at a time value increment and (a+0) this means after again come then the value is increase