By Dinah


2008-12-19 17:01:33 8 Comments

As Joel points out in Stack Overflow podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]

Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]?

18 comments

@dgnuff 2019-04-08 18:45:49

A little bit of history now. Among other languages, BCPL had a fairly major influence on C's early development. If you declared an array in BCPL with something like:

let V = vec 10

that actually allocated 11 words of memory, not 10. Typically V was the first, and contained the address of the immediately following word. So unlike C, naming V went to that location and picked up the address of the zeroeth element of the array. Therefore array indirection in BCPL, expressed as

let J = V!5

really did have to do J = !(V + 5) (using BCPL syntax) since it was necessary to fetch V to get the base address of the array. Thus V!5 and 5!V were synonymous. As an anecdotal observation, WAFL (Warwick Functional Language) was written in BCPL, and to the best of my memory tended to use the latter syntax rather than the former for accessing the nodes used as data storage. Granted this is from somewhere between 35 and 40 years ago, so my memory is a little rusty. :)

The innovation of dispensing with the extra word of storage and having the compiler insert the base address of the array when it was named came later. According to the C history paper this happened at about the time structures were added to C.

Note that ! in BCPL was both a unary prefix operator and a binary infix operator, in both cases doing indirection. just that the binary form included an addition of the two operands before doing the indirection. Given the word oriented nature of BCPL (and B) this actually made a lot of sense. The restriction of "pointer and integer" was made necessary in C when it gained data types, and sizeof became a thing.

@Jeet Parikh 2018-07-13 07:34:11

pointer types

1) pointer to data

int *ptr;

2) const pointer to data

int const *ptr;

3) const pointer to const data

int const *const ptr;

and the arrays are type of (2) from our list
When you define an array at a time one address is initialize in that pointer
As we know that we can't change or modify const value in our program cause it's throws an ERROR at compile time

The major difference I found is...

We can re-initialize the pointer by an address but not the same case with an array.

======
and back to your question...
a[5] is nothing but *(a + 5)
you can understand easily by
a - containing address (people call it as base address) just like an (2) type of pointer in our list
[] - that operator can be replaceable with pointer * .

so finally...

a[5] == *(a +5) == *(5 + a) == 5[a] 

@melpomene 2018-10-02 05:06:02

Arrays are not pointers.

@Harsha J K 2018-04-02 18:42:27

Well, this is a feature that is only possible because of the language support.

The compiler interprets a[i] as *(a+i) and the expression 5[a] evaluates to *(5+a). Since addition is commutative it turns out that both are equal. Hence the expression evaluates to true.

@Jayghosh Wankar 2017-02-12 13:54:41

In C

 int a[]={10,20,30,40,50};
 int *p=a;
 printf("%d\n",*p++);//output will be 10
 printf("%d\n",*a++);//will give an error

Pointer is a "variable"

array name is a "mnemonic" or "synonym"

p++; is valid but a++ is invalid

a[2] is equals to 2[a] because the internal operation on both of this is

"Pointer Arithmetic" internally calculated as

*(a+3) equals *(3+a)

@James Curran 2008-12-19 17:07:17

And, of course

 ("ABCD"[2] == 2["ABCD"]) && (2["ABCD"] == 'C') && ("ABCD"[2] == 'C')

The main reason for this was that back in the 70's when C was designed, computers didn't have much memory (64KB was a lot), so the C compiler didn't do much syntax checking. Hence "X[Y]" was rather blindly translated into "*(X+Y)"

This also explains the "+=" and "++" syntaxes. Everything in the form "A = B + C" had the same compiled form. But, if B was the same object as A, then an assembly level optimization was available. But the compiler wasn't bright enough to recognize it, so the developer had to (A += C). Similarly, if C was 1, a different assembly level optimization was available, and again the developer had to make it explicit, because the compiler didn't recognize it. (More recently compilers do, so those syntaxes are largely unnecessary these days)

@Jonathan Leffler 2008-12-19 17:16:12

Actually, that evaluates to false; the first term "ABCD"[2] == 2["ABCD"] evaluates to true, or 1, and 1 != 'C' :D

@Dinah 2008-12-19 17:26:03

@Jonathan: same ambiguity lead to the editing of the original title of this post. Are we the equal marks mathematical equivalency, code syntax, or pseudo-code. I argue mathematical equivalency but since we're talking about code, we can't escape that we're viewing everything in terms of code syntax.

@Thomas Padron-McCarthy 2008-12-19 17:44:13

Isn't this a myth? I mean that the += and ++ operators were created to simplify for the compiler? Some code gets clearer with them, and it is useful syntax to have, no matter what the compiler does with it.

@Johannes Schaub - litb 2008-12-19 17:49:27

+= and ++ has another significant benefit. if the left hand side changes some variable while evaluated, the change will only done once. a = a + ...; will do it twice.

@Liran Orevi 2009-04-21 08:02:28

Heard that += reduces the odds for mistakes as you write variable names two times rather than three...

@jkeys 2009-08-12 21:49:22

a = a + with objects often leads to unoptimized copies of the objects, because it has to make a copy of a. a += does not need a copy, it is evaluated directly.

@knittl 2009-09-21 10:05:33

doesn’t "ABCD"[2] resolve to "CD"? if you want it to resolve to 'C' you’d have to use dereferencing, i.e. *("ABCD"[2]) == 'C')

@MSalters 2009-09-21 10:34:38

No - "ABCD"[2] == *("ABCD" + 2) = *("CD") = 'C'. Dereferencing a string gives you a char, not a substring

@Dennis Zickefoose 2011-06-19 09:44:06

"It'll be easier to implement this way" makes a whole lot more sense then "mathematically it works, so even though it serves no practical purpose whatsoever, lets add it to the language" as a rational.

@dave 2012-05-03 02:26:47

Algol68, as far as I recall, was the origin of combined arithmetic-and-assignation operators, as in foo +:= bar, pronounced 'foo plus-and-becomes bar'. I believe the rationale was that this more closely resembled what one wanted to do in the first place, namely 'add bar to foo' (though why we didn't get bar =:+ foo out of that logic, I don't know).

@John Bode 2012-05-03 15:19:17

@ThomasPadron-McCarthy: From here: "During development, [Thompson] continually struggled against memory limitations: each language addition inflated the compiler so it could barely fit, but each rewrite taking advantage of the feature reduced its size. For example, B introduced generalized assignment operators, using x=+y to add y to x...Thompson went a step further by inventing the ++ and -- operators...a stronger motivation for the innovation was probably his observation that the translation of ++x was smaller than that of x=x+1."

@James Curran 2013-01-24 14:14:20

@dave: It's x += 5; rather than x =+ 5; because the latter would be parsed as x = (+5);

@Vatine 2013-04-18 15:58:13

@JamesCurran I am pretty sure it started out as LHS =- RHS; and was eventually swapped to use -=.

@EvilTeach 2013-10-07 02:30:06

++ frequently mapped to a single machine instruction while x = x + 1 could be more than one. x += 3 maps to less machine instructions that x = x + 3 as the knowledge is that one will pick up x once, add three to it and drop it back down. register int x = 3 is from that same era, when compilers weren't as smart as they are today.

@Miles Rout 2014-06-17 15:57:54

@JamesCurran the unary + didn't exist in early C.

@James Curran 2014-07-01 19:22:09

@MilesRout : Perhaps not, but unary minus definitely did, leading to the same problem.

@Soren 2014-08-27 23:33:53

The PDP11 mini computer (PDP were used for the first C and UNIX operating system) had assembly instructions for += -= ++ -- so while there may have been forerunners in Algol, there were a bit of 1-to-1 mapping between instruction set and language capabilities.

@user743382 2014-11-15 12:33:03

@Vatine is right, it was =+ before +=. The B programming language (which I'm surprised to read is still used), ancestor of C, uses the =+ form. IIRC, the main reason for changing it was that i=-1; was ambiguous. Not ambiguous to the compiler, but to human readers who had trouble understanding whether this was supposed to decrease i by 1 (and hence correctly written), or whether this was supposed to assign -1 to i (and hence a bug in the code). Disclaimer: my recollection may be faulty.

@user207421 2016-01-25 22:47:41

@JohnBode The quoted sentence beginning 'a stronger motivation for the innovation ...' is just circular reasoning. He couldn't have noticed it before he innovated it. The fact is that the PDP-11 had both pre-increment and post-decrement instructions, or possibly the other way around, it's been 37 years.

@user4624979 2016-07-11 18:45:30

So, if ++ is largely unnecessary, is C++ largely unnecessary? I am holding out for C###, myself.

@franji1 2017-07-28 17:54:51

@Dinah, agreed, so edited accordingly

@A.s. Bhullar 2013-09-27 06:46:44

It has very good explanation in A TUTORIAL ON POINTERS AND ARRAYS IN C by Ted Jensen.

Ted Jensen explained it as:

In fact, this is true, i.e wherever one writes a[i] it can be replaced with *(a + i) without any problems. In fact, the compiler will create the same code in either case. Thus we see that pointer arithmetic is the same thing as array indexing. Either syntax produces the same result.

This is NOT saying that pointers and arrays are the same thing, they are not. We are only saying that to identify a given element of an array we have the choice of two syntaxes, one using array indexing and the other using pointer arithmetic, which yield identical results.

Now, looking at this last expression, part of it.. (a + i), is a simple addition using the + operator and the rules of C state that such an expression is commutative. That is (a + i) is identical to (i + a). Thus we could write *(i + a) just as easily as *(a + i). But *(i + a) could have come from i[a] ! From all of this comes the curious truth that if:

char a[20];

writing

a[3] = 'x';

is the same as writing

3[a] = 'x';

@Alex Brown 2015-12-04 20:17:46

a+i is NOT simple addition, because it's pointer arithmetic. if the size of the element of a is 1 (char), then yes, it's just like integer +. But if it's (e.g.) an integer, then it might be equivalent to a + 4*i.

@jschultz410 2018-03-21 16:11:28

@AlexBrown Yes, it is pointer arithmetic, which is exactly why your last sentence is wrong, unless you first cast 'a' to be a (char*) (assuming that an int is 4 chars). I really don't understand why so many people are getting hung up on the actual value result of pointer arithmetic. Pointer arithmetic's entire purpose is to abstract away the underlying pointer values and let the programmer think about the objects being manipulated rather than address values.

@Mehrdad Afshari 2008-12-19 17:04:16

The C standard defines the [] operator as follows:

a[b] == *(a + b)

Therefore a[5] will evaluate to:

*(a + 5)

and 5[a] will evaluate to:

*(5 + a)

a is a pointer to the first element of the array. a[5] is the value that's 5 elements further from a, which is the same as *(a + 5), and from elementary school math we know those are equal (addition is commutative).

@John MacIntyre 2008-12-19 17:06:42

I wonder if it isn't more like *((5 * sizeof(a)) + a). Great explaination though.

@John MacIntyre 2008-12-19 17:10:02

I'm totally anal ... so I couldn't resist. ... the assignment operator in the title is also driving me bananas ... but I'm not going going to be that big of a knob. ;-)

@Dinah 2008-12-19 17:11:59

Sorry that the "assignment operator" is driving you nuts, however I'm asking about mathematical equivalency not representing a code snippet so the equals sign is correct. Thanks for the answers!

@Dinah 2008-12-19 17:15:12

Why is sizeof() taken into account. I thought the pointer to 'a' is to the beginning of the array (ie: the 0 element). If this is true, you only need *(a + 5). My understanding must be incorrect. What's the correct reason?

@Treb 2008-12-19 17:17:56

If you have an array of 4 byte integers, a[1] - a[0] = 4 (4 bytes dieffernce between the two pointers).

@Mehrdad Afshari 2008-12-19 17:18:23

@Dinah: From a C-compiler perspective, you are right. No sizeof is needed and those expressions I mentioned are THE SAME. However, the compiler will take sizeof into account when producing machine code. If a is an int array, a[5] will compile to something like mov eax, [ebx+20] instead of [ebx+5]

@James Curran 2008-12-19 17:21:39

@Dinah: A is an address, say 0x1230. If a was in 32-bit int array, then a[0] is at 0x1230, a[1] is at 0x1234, a[2] at 0x1238...a[5] at x1244 etc. If we just add 5 to 0x1230, we get 0x1235, which is wrong.

@Dinah 2008-12-19 17:27:45

@James: bingo. That's what I needed to see. I kept seeing sizeof() and thinking count() and getting mightily confused. Not my brightest moment. Thank you!

@John MacIntyre 2008-12-19 18:25:10

@Dinah; the assignment operator comment was just a tongue-in-cheek comment about how anal I am. ;-) ... I knew what you meant, and I'm sure everybody else did as well. Great question btw, I was just listening to the SO podcast where they were talking about it.

@Harvey 2008-12-22 18:27:34

So in the 5[a] case, the compiler is smart enough to use "*((5 * sizeof(a)) + a)" and not "*(5 + (a * sizeof(5)))"? Note: I guess so. I tried this in GCC and it worked.

@aib 2008-12-23 02:08:05

@sr105: That's a special case for the + operator, where one of the operands is a pointer and the other an integer. The standard says that the result will be of the type of the pointer. The compiler /has to be/ smart enough.

@johnc 2009-03-03 08:01:17

comments never floated to the top in my memory

@araqnid 2009-04-18 01:03:25

When you add an integer to a pointer, the compiler knows what type the pointer points to (so if a is an int*, it's 4 bytes or whatever...) so can perform the arithmetic right. Basically if you do "p++" then p should be adjusted to point to the next object in memory. "p++" is basically equivalent to "p = p + 1", so the definition of pointer addition makes everything line up. Also note you can't do arithmetic with pointers of type void*.

@Mehrdad Afshari 2009-09-21 16:25:06

@litb: I understand your concern and potentially "misleading" people. However, I wanted to keep simplicity of the answer, as in this context, the array decays to a pointer. I changed "being a pointer" to "behaving as pointers." I hope that's OK. Thanks for the comment, btw.

@Fahad Sadah 2010-05-23 12:16:49

freeworld.thc.org/root/phun/unmaintain.html mentions this as a good tactic for obfuscation, giving the example myfunc(6291, 8)[Array]; where myfunc is simply the modulo function (that's equivalent to Array[3])

@Amarghosh 2010-11-12 05:33:46

@Mehrdad I think the main reason behind this post getting upvoted more than that exploit post (which definitely deserves to be on the top) is that this one addresses a relatively simpler problem and hence more people tend to understand this. The anatomy of the exploit is not this simple and most people will just skip it :)

@LarsH 2010-12-01 20:54:34

"from elementary school math we know those are equal" - I understand that you are simplifying, but I'm with those who feel like this is oversimplifying. It's not elementary that *(10 + (int *)13) != *((int *)10 + 13). In other words, there's more going on here than elementary school arithmetic. The commutativity relies critically on the compiler recognizing which operand is a pointer (and to what size of object). To put it another way, (1 apple + 2 oranges) = (2 oranges + 1 apple), but (1 apple + 2 oranges) != (1 orange + 2 apples).

@Mehrdad Afshari 2010-12-01 21:53:28

@LarsH: You're right. I'd say it's more analogous to (10in + 10cm) rather than apples and oranges (you can meaningfully convert one to another).

@LarsH 2010-12-01 23:37:43

@Mehrdad: Fair enough. Maybe a better analogy is a date vs. a time interval, as in (May 1st 2010 + 3 weeks).

@Lightness Races in Orbit 2011-08-14 15:14:15

"This is the direct artifact of arrays behaving as pointers": no, arrays do not behave as pointers at all.

@Lightness Races in Orbit 2011-08-14 15:14:44

'"a" is a memory address': no, no more than x is a memory address if you write int x;. The name of the array can decay to a pointer to the first element of that array, though.

@Mehrdad Afshari 2011-08-14 22:21:57

@Tomalak I understand. There are plenty of places that it was relevant and we've discussed it. However, while the question specifically asks about the reason why it works the way it does. I can't imagine this being the behavior of 5[a] if in the original implementation of C, pointers weren't really binaries representing memory addresses directly understandable by the CPU. If we want to be too pedantic, the answer (to this question and many more) is: "Because the standard defines the behavior of [] operator on int types on one side and array or pointer types on another as such."

@Ben Voigt 2013-04-05 17:27:53

@Jim: No, it's because the types, not the values, are the same. Furthermore, elementary school arithmetic cannot be applied blindly to arithmetic operators. Consider INT_MAX - 5 + 1 vs INT_MAX + 1 - 5.

@Ben Voigt 2013-04-05 21:44:33

@Jim: Hardly. The type of a and the type of 99 are certainly not the same in this question.

@Ben Voigt 2013-04-06 00:38:50

@Jim: What is it called when you edit your comment in order to make my response look stupid? You just have to look up a few comments, to see that type DOES matter. (10 + (int *)13) != ((int *)10 + 13) and that was already pointed out.

@Ben Voigt 2013-04-06 00:41:09

Also, my claim that "elementary school arithmetic cannot be applied blindly to arithmetic operators" needs only one example to prove that further consideration, not blind application, is necessary. And I can provide several examples. Here's another case where type is important: T a = 7.0; double x = a / 2.0; Clearly whether a is int or double makes a huge difference in the answer.

@Ben Voigt 2013-04-06 00:45:08

More examples are possible, due to limited range and precision of floating-point types. The example I chose originally, I chose because it involves integer addition, same as the problem under discussion.

@Dukeling 2013-07-30 10:36:54

@BenVoigt Actually I think your example should be double x = a / 2;. If it's 2.0 the result will be double, regardless of whether a is an int or a double.

@hamstergene 2014-06-28 20:36:13

What exactly in elementary school arithmetics says that adding values of completely different types must always be commutative?

@Mehrdad Afshari 2014-06-30 01:53:24

@hamstergene Elementary school math does not talk about types. My answer to the OP question for you would be The One and Only True Answer: "because the C standard says so."

@Bolun Zhang 2014-07-17 17:35:47

@JohnMacIntyre Even if it isn't automatically incremented, shouldn't it be *((5 * sizeof(*a)) + a) instead of *((5 * sizeof(a)) + a)?

@Jean-Baptiste Yunès 2014-11-18 08:19:32

from elementary school math we know those are equal, well it's true that we learn that addition is commutative, but in the case of values of the same type! So it is not obvious that adding a pointer and an integer is a commutative operation! But this is defined by the standard... This is no less obvious than adding 5 to an address does not give address+5, but address+5*sizeof(type)! So pointer arithmetic is not so obvious.

@Mehrdad Afshari 2014-11-19 03:09:33

@Jean-BaptisteYunès Yes. The technical answer to the question is "because the language specification says *(p+5) is equal to *(5+p) and a[b] equals *(a+b)". However, the rationale for *(p+5) being equal to *(5+p) is indeed consistency with "elementary school math".

@Jean-Baptiste Yunès 2014-11-19 06:58:10

For sure, but consistent with elementary math is not a requirement in pointer arithmetic. The sum is "typed" with the pointer's type so it is not so "natural", so why would you like it to be commutative ? Just because the code produced in assembly doesn't have type ?

@Mehrdad Afshari 2014-11-19 07:21:55

@Jean-BaptisteYunès It's not a requirement. It is a design decision the C language designers made presumably to remain consistent with commutativity of the addition operator. Sure, nothing is required in the strictest sense when you are designing a language.

@CiaPan 2016-04-14 09:28:08

@Jean-BaptisteYunès & Mehrdad Afshari: May be it's worth mentioning that in assembly languages we sometimes use a constant base address of a table and a calculated offset to select an array's item, and sometimes we have a constant offset to a member of a dynamically allocated structure. And both types of access, const[var] and var[const] are translated to the same CPU instruction. Possibly C, as a quite low-level among high-level languages, deliberately inherits this equivalence.

@dgnuff 2018-04-18 23:14:45

A little history may help explain why this is the way that it is. As noted here: gotw.ca/conv/003.htm C and C++ have their origins in BCPL. BCPL used ! (aka pling) as the indirection operator, and it took two forms, unary and binary. !a unary has the same meaning as *a does in C/C++, i.e. unary indirection. a!b binary is used for array lookup, equivalent to a[b] in C. Since binary ! is commutative in BCPL, and has the same effect as !(a + b) I very strongly suspect this is why array indirection has the same commutative behavior in C/C++.

@Mehrdad Afshari 2018-04-19 06:51:45

@dgnuff Wow, thanks!

@Jan Christoph Terasa 2018-11-08 06:00:34

Why is it syntactically allowed to index integer literals by the standard? I cannot see how anyone would write this intentionally. The standard probably allows it because adding a check will make a compiler parser/lexer slightly more complex. But I think in today's world the speed impact on compilation will be minimal, while catching unintentional behaviour is very useful. Newer versions of GCC even warn about fall-through in switches, which has an actual intentional use. So IMHO compilers should at least warn about this. GCC 8.2 does not give a warning even with -Wall.

@Ajinkya Patil 2016-05-04 08:24:29

I know the question is answered, but I couldn't resist sharing this explanation.

I remember Principles of Compiler design, Let's assume a is an int array and size of int is 2 bytes, & Base address for a is 1000.

How a[5] will work ->

Base Address of your Array a + (5*size of(data type for array a))
i.e. 1000 + (5*2) = 1010

So,

Similarly when the c code is broken down into 3-address code, 5[a] will become ->

Base Address of your Array a + (size of(data type for array a)*5)
i.e. 1000 + (2*5) = 1010 

So basically both the statements are pointing to the same location in memory and hence, a[5] = 5[a].

This explanation is also the reason why negative indexes in arrays work in C.

i.e. if I access a[-5] it will give me

Base Address of your Array a + (-5 * size of(data type for array a))
i.e. 1000 + (-5*2) = 990

It will return me object at location 990.

@Keith Thompson 2013-08-23 01:37:17

I think something is being missed by the other answers.

Yes, p[i] is by definition equivalent to *(p+i), which (because addition is commutative) is equivalent to *(i+p), which (again, by the definition of the [] operator) is equivalent to i[p].

(And in array[i], the array name is implicitly converted to a pointer to the array's first element.)

But the commutativity of addition is not all that obvious in this case.

When both operands are of the same type, or even of different numeric types that are promoted to a common type, commutativity makes perfect sense: x + y == y + x.

But in this case we're talking specifically about pointer arithmetic, where one operand is a pointer and the other is an integer. (Integer + integer is a different operation, and pointer + pointer is nonsense.)

The C standard's description of the + operator (N1570 6.5.6) says:

For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type.

It could just as easily have said:

For addition, either both operands shall have arithmetic type, or the left operand shall be a pointer to a complete object type and the right operand shall have integer type.

in which case both i + p and i[p] would be illegal.

In C++ terms, we really have two sets of overloaded + operators, which can be loosely described as:

pointer operator+(pointer p, integer i);

and

pointer operator+(integer i, pointer p);

of which only the first is really necessary.

So why is it this way?

C++ inherited this definition from C, which got it from B (the commutativity of array indexing is explicitly mentioned in the 1972 Users' Reference to B), which got it from BCPL (manual dated 1967), which may well have gotten it from even earlier languages (CPL? Algol?).

So the idea that array indexing is defined in terms of addition, and that addition, even of a pointer and an integer, is commutative, goes back many decades, to C's ancestor languages.

Those languages were much less strongly typed than modern C is. In particular, the distinction between pointers and integers was often ignored. (Early C programmers sometimes used pointers as unsigned integers, before the unsigned keyword was added to the language.) So the idea of making addition non-commutative because the operands are of different types probably wouldn't have occurred to the designers of those languages. If a user wanted to add two "things", whether those "things" are integers, pointers, or something else, it wasn't up to the language to prevent it.

And over the years, any change to that rule would have broken existing code (though the 1989 ANSI C standard might have been a good opportunity).

Changing C and/or C++ to require putting the pointer on the left and the integer on the right might break some existing code, but there would be no loss of real expressive power.

So now we have arr[3] and 3[arr] meaning exactly the same thing, though the latter form should never appear outside the IOCCC.

@Dinah 2013-08-24 01:01:54

Fantastic description of this property. From a high level view, I think 3[arr] is an interesting artifact but should rarely if ever be used. The accepted answer to this question (<stackoverflow.com/q/1390365/356>) which I asked a while back has changed the way I've thought about syntax. Although there's often technically not a right and wrong way to do these things, these kinds of features start you thinking in a way which is separate from the implementation details. There's benefit to this different way of thinking which is in part lost when you fixate on the implementation details.

@iheanyi 2014-04-21 17:54:14

Addition is commutative. For the C standard to define it otherwise would be strange. That's why it could not just as easily said "For addition, either both operands shall have arithmetic type, or the left operand shall be a pointer to a complete object type and the right operand shall have integer type." - That wouldn't make sense to most people who add things.

@Keith Thompson 2014-04-21 18:13:58

@iheanyi: Addition is usually commutative -- and it usually takes two operands of the same type. Pointer addition lets you add a pointer and an integer, but not two pointers. IMHO that's already a sufficiently odd special case that requiring the pointer to be the left operand wouldn't be a significant burden. (Some languages use "+" for string concatenation; that's certainly not commutative.)

@iheanyi 2014-04-21 19:53:57

True on the string example! In that light, this looks like a language decision that comes from the implementation side of things - rather than design.

@supercat 2014-10-20 16:08:04

@iheanyi: Addition of numbers is commutative, but that doesn't mean that addition must be commutative with things that are not numbers. It was not uncommon for assemblers to require that every address involving a relocatable symbol must be of the exact form "rel_symbol", "rel_symbol + number", or "rel_symbol - number", since the linker would expect a list of fix-ups, each of which identified a "base" symbol and the place where it was used (the pre-fixed-up code would hold the number to be added to the symbol).

@supercat 2014-10-20 16:18:07

@iheanyi: I think it's cleaner from a rules perspective to say that the second operand of an addition operator must be a number, and the result type will match the first operand, than to try to say that "at least one" operand must be a number. Incidentally, a lot of annoyances related to unsigned types could have been eliminated if the addition operator always returned the type of its left-hand operand, rather than saying that given uint32_t x=0; the value of x-1 must on some implementations yield 4294967295 and on others yield -1.

@iheanyi 2014-10-21 16:34:59

@supercat, That's even worse. That would mean that sometimes x + 1 != 1 + x. That would completely violate the associative property of addition.

@supercat 2014-10-21 16:46:00

@iheanyi: I think you meant commutative property; addition is already not associative, since on most implementations (1LL+1U)-2 != 1LL+(1U-2). Indeed, the change would make some situations associative which presently aren't, e.g. 3U+(UINT_MAX-2L) would equal (3U+UINT_MAX)-2. What would be best, though, is for the language to have add new distinct types for promotable integers and "wrapping" algebraic rings, so that adding 2 to a ring16_t which holds 65535 would yield a ring16_t with value 1, independent of the size of int.

@iheanyi 2014-10-21 16:59:59

@supercat - thanks for that response. That clarifies the issues at hand with a good example :)

@L. F. 2019-05-01 14:04:48

Concerning C++, it should be mentioned that user-defined operator overloads aren't subject to the same rule: vec[5] is fine, whereas 5[vec] is an error.

@Keith Thompson 2019-05-01 17:58:52

@L.F.: I think it's possible to provide an overload such that 5[vec] is valid (and might have a different meaning than vec[5]. (I'll have to check that.) But the question is tagged "c", so I didn't go into that.

@L. F. 2019-05-01 23:31:49

@KeithThompson Well, theoretically you can provide an implicit conversion to T*, but that's against the idea of vectors.

@Ajay 2011-06-19 08:37:16

Not an answer, but just some food for thought. If class is having overloaded index/subscript operator, the expression 0[x] will not work:

class Sub
{
public:
    int operator [](size_t nIndex)
    {
        return 0;
    }   
};

int main()
{
    Sub s;
    s[0];
    0[s]; // ERROR 
}

Since we dont have access to int class, this cannot be done:

class int
{
   int operator[](const Sub&);
};

@Ben Voigt 2013-04-05 17:23:11

class Sub { public: int operator[](size_t nIndex) const { return 0; } friend int operator[](size_t nIndex, const Sub& This) { return 0; } };

@Ajay 2013-04-05 21:10:03

Have you actually tried compiling it? There are set of operators that cannot be implemented outside class (i.e. as non-static functions)!

@Ben Voigt 2013-04-05 21:21:37

oops, you're right. "operator[] shall be a non-static member function with exactly one parameter." I was familiar with that restriction on operator=, didn't think it applied to [].

@Luis Colorado 2014-09-19 13:18:17

Of course, if you change the definition of [] operator, it would never be equivalent again... if a[b] is equal to *(a + b) and you change this, you'll have to overload also int::operator[](const Sub&); and int is not a class...

@MD XF 2016-12-13 07:13:46

This...isn't...C.

@AVIK DUTTA 2014-10-29 09:14:54

in c compiler

a[i]
i[a]
*(a+i)

are different ways to refer to an element in an array ! (NOT AT ALL WEIRD)

@Krishan 2013-12-17 11:22:08

In C arrays, arr[3] and 3[arr] are the same, and their equivalent pointer notations are *(arr + 3) to *(3 + arr). But on the contrary [arr]3 or [3]arr is not correct and will result into syntax error, as (arr + 3)* and (3 + arr)* are not valid expressions. The reason is dereference operator should be placed before the address yielded by the expression, not after the address.

@Frédéric Terrazzoni 2012-06-10 19:50:54

I just find out this ugly syntax could be "useful", or at least very fun to play with when you want to deal with an array of indexes which refer to positions into the same array. It can replace nested square brackets and make the code more readable !

int a[] = { 2 , 3 , 3 , 2 , 4 };
int s = sizeof a / sizeof *a;  //  s == 5

for(int i = 0 ; i < s ; ++i) {  

           cout << a[a[a[i]]] << endl;
           // ... is equivalent to ... 
           cout << i[a][a][a] << endl;  // but I prefer this one, it's easier to increase the level of indirection (without loop)

}

Of course, I'm quite sure that there is no use case for that in real code, but I found it interesting anyway :)

@Luis Colorado 2014-09-19 13:14:49

Oh God!!! how can somebody say that prefers that notation!!! It hurts my eyes!!!

@12431234123412341234123 2018-05-14 11:58:02

When you see i[a][a][a] you think i is either a pointer to an array or an array of a pointer to an array or a array ... and a is a index. When you see a[a[a[i]]], you think a is a pointer to a array or a array and i is a index.

@Serge Breusov 2018-06-28 08:53:18

Wow! It's very cool usage of this "stupid" feature. Could be useful in algorithmic contest in some problems))

@user1287577 2012-03-23 07:05:27

For pointers in C, we have

a[5] == *(a + 5)

and also

5[a] == *(5 + a)

Hence it is true that a[5] == 5[a].

@Peter Lawrey 2011-08-11 13:50:22

To answer the question literally. It is not always true that x == x

double zero = 0.0;
double a[] = { 0,0,0,0,0, zero/zero}; // NaN
cout << (a[5] == 5[a] ? "true" : "false") << endl;

prints

false

@TrueY 2013-04-23 09:34:43

Actually a "nan" is not equal to itself: cout << (a[5] == a[5] ? "true" : "false") << endl; is false.

@Tim Čas 2015-02-13 01:04:07

@TrueY: He did state that specifically for the NaN case (and specifically that x == x is not always true). I think that was his intention. So he is technically correct (and possibly, as they say, the best kind of correct!).

@12431234123412341234123 2018-05-14 16:02:41

The question is about C, your code is not C code. There is also a NAN in <math.h>, which is better than 0.0/0.0, because 0.0/0.0 is UB when __STDC_IEC_559__ is not defined (Most implementations do not define __STDC_IEC_559__, but on most implementations 0.0/0.0 will still work)

@David Thornley 2008-12-19 17:05:01

Because array access is defined in terms of pointers. a[i] is defined to mean *(a + i), which is commutative.

@Lightness Races in Orbit 2011-05-12 23:20:41

Arrays are not defined in terms of pointers, but access to them is.

@Jim Balter 2013-04-05 22:11:18

I would add "so it is equal to *(i + a), which can be written as i[a]".

@Vality 2015-02-17 21:41:13

I would suggest you include the quote from the standard, which is as follows: 6.5.2.1: 2 A postfix 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).

@12431234123412341234123 2018-05-14 16:11:00

To be more correct: Arrays decay into pointers when you access them.

@user30364 2009-02-11 15:56:20

One thing no-one seems to have mentioned about Dinah's problem with sizeof:

You can only add an integer to a pointer, you can't add two pointers together. That way when adding a pointer to an integer, or an integer to a pointer, the compiler always knows which bit has a size that needs to be taken into account.

@Dinah 2009-04-21 13:51:49

There's a fairly exhaustive conversation about this in the comments of the accepted answer. I referenced said conversation in the edit to the original question but did not directly address your very valid concern of sizeof. Not sure how to best do this in SO. Should I make another edit to the orig. question?

@PolyThinker 2008-12-20 08:16:20

Nice question/answers.

Just want to point out that C pointers and arrays are not the same, although in this case the difference is not essential.

Consider the following declarations:

int a[10];
int* p = a;

In a.out, the symbol a is at an address that's the beginning of the array, and symbol p is at an address where a pointer is stored, and the value of the pointer at that memory location is the beginning of the array.

@PolyThinker 2008-12-22 05:42:16

No, technically they are not the same. If you define some b as int*const and make it point to an array, it is still a pointer, meaning that in the symbol table, b refers to a memory location that stores an address, which in turn points to where the array is.

@Giorgio 2012-05-02 18:15:33

Very good point. I remember having a very nasty bug when I defined a global symbol as char s[100] in one module, declare it as extern char *s; in another module. After linking it all together the program behaved very strangely. Because the module using the extern declaration was using the initial bytes of the array as a pointer to char.

@dave 2012-05-03 02:33:10

Originally, in C's grandparent BCPL, an array was a pointer. That is, what you got when you wrote (I have transliterated to C) int a[10] was a pointer called 'a', which pointed to enough store for 10 integers, elsewhere. Thus a+i and j+i had the same form: add the contents of a couple of memory locations. In fact, I think BCPL was typeless, so they were identical. And the sizeof-type scaling did not apply, since BCPL was purely word-oriented (on word-addressed machines also).

@James Curran 2013-03-12 16:34:28

I think the best way to understand the difference is to compare int*p = a; to int b = 5; In the latter, "b" and "5" are both integers, but "b" is a variable, while "5" is a fixed value. Similarly, "p" & "a" are both addresses of a character, but "a" is a fixed value.

Related Questions

Sponsored Content

38 Answered Questions

[SOLVED] Deleting an element from an array in PHP

  • 2008-12-15 20:28:55
  • Ben
  • 2287775 View
  • 2254 Score
  • 38 Answer
  • Tags:   php arrays

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5772064 View
  • 7203 Score
  • 79 Answer
  • Tags:   javascript arrays

10 Answered Questions

[SOLVED] Improve INSERT-per-second performance of SQLite?

39 Answered Questions

[SOLVED] Loop through an array in JavaScript

32 Answered Questions

[SOLVED] Create ArrayList from array

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

44 Answered Questions

[SOLVED] How to check if an object is an array?

46 Answered Questions

30 Answered Questions

[SOLVED] How to append something to an array?

14 Answered Questions

[SOLVED] How to insert an item into an array at a specific index (JavaScript)?

Sponsored Content