4 ms·
a[5] == 5[a]
- pyre 15y agoThat explanation only partially works. a[5] evaluates to something like: *(a + (sizeof(a) * 5)) so shouldn't 5[a] evaluate to *(5 + (sizeof(5) * a)) Those don't seem equivalent, unless I'm missing something.
- jackowayed 15y agoIt works if you think of it as expanding to *(a + 5). Pointer addition is defined to be scaled by the size of the pointer.
- deleted 15y ago[deleted]
- deleted 15y ago[deleted]
- lurker19 15y agoThat behavior of "+" is defined in the standard, so you don't have to worry about which conforming compiler you are using. Adding integers to pointers can't be a syntax error, since otherwise arrays would be impossible. The commutativity of the bracket operator is a silly side effect of the commutativity of addition, but not broken in any way except maybe readability.
- lurker19 15y agoIt is also interesting to note that this behavior of '+' in C an C++ and Java is basically (logically) multiple-dispatch on the types of its arguments, but the language does not allow programmers to define operators like this -- C does not allow user-defined operators at all, in C++ you have to define the operator in every class that can appear on the left-hand-side, in Java you can define a method which looks almost like an operator but still has to be smeared across all classes (unless you write a utility class method Foo.plus(A, B) that eliminates the asymmetry between the two operands). This subordination of functions below objects, and special reservation of rights for builtins, is what functional programming language uses loath about non-FP languages.
- lurker19 15y agoAs noted in the SO comments: when compiling the "+", the compiler uses the sizeof of the referenced type of whichever addend is actually a pointer.
- pyre 15y agoI think that I've been away from statically-typed languages for too long. I was just thinking of the pointer as an int whose value just happens to be a memory address and forgetting that the compiler knows it's a pointer.
- lurker19 15y agoTo first order approximation, C is the language with no magic. That's its most beloved quality. That gets you really far, until you get creamed by all the subtle magic in pointers and arrays.
- lurker19 15y agoThis works just as well in dynamically typed language by using your language's version of .getClass() or instanceof. It would just happen at runtime instead of compile time. It only wouldn't work in very weakly typed languages like ... assembler?
- pyre 15y agoI was evaluating 5 + a to mean int + int, because the pointer is stored in an int. Maybe I should have just stated, "It's been awhile since I've work with pointers." Most dynamic languages don't have a concept of pointers, or at least not pointer math.
- barrkel 15y agoNo; a[5] evaluates to (a + 5), and 5[a] as (5 + a). Separately: e + p where e : integer-type and p : pointer-type p + e where e : integer-type and p : pointer-type are evaluated roughly as: (pointer-type)(e*sizeof(*p) + (size_t)p) (pointer-type)((size_t)p + e*sizeof(*p)) but these are very rough translations, because we're wandering into implementation-defined territory (substitute uintptr_t for size_t as desired etc). The type analysis on the addition is reminiscent of e.g. promoting integers to floats: i + f where i : integer-type and f : float-type f + i where i : integer-type and f : float-type correspondingly: (float-type)i float-type::+ f f float-type::+ (float-type)i The '+' built-in is overloaded in C.
- guyzero 15y agoI suppose this is an evergreen topic for new C programmers. I find it surprising that HN is posting something that's basically a verbatim quote from K&R which was first published in 1978. a 33 year-old C hack ain't news. Than again, I guess the days where you could assume everyone who knew how to program programmed in C are long gone.
- pyre 15y agoYou're also assuming that everyone that knows how to program in C has read K&R. That's like assuming that everyone that knows how to program has read the Art of Computer Programming.
- comatose_kid 15y agoInteresting comparison! Let's take a look: TAOCP Vol 1 Amazon rank: 364,370. K&R C Amazon rank: 2307 Based on the above, and also that C programmers are a subset of everyone that knows how to program, it seems that the two ratios would be off by a few orders of magnitude. So I don't think this comparison is really correct. I'll add to this my anecdotal experience that about half of the people I have worked with who call themselves C programmers have read K&R.
- guyzero 15y agoI learned C from Kochan (1st Ed) so it is indeed fair to say that it's a big assumption that every C programmer has read K&R, even for us grognards.
- mkelly 15y agoI agree. I posted a crazy rant elsewhere in the comments, actually, prompted by the same thoughts. Poor HN.
- Natsu 15y agoIt would be familiar to anyone who has read IOCCC submissions or K&R, I should think. But it's quite surprising for just about everyone else, I think. Does any other language allow this? I think JavaScript allows some syntactic contortions, but I don't remember offhand if it permits this particular one.
- mkelly 15y agoWarning: crazy rant coming. So this is what HN has degenerated to? I'm sorry, but I remember eagerly reading the front page, learning things from interesting articles, and -- more importantly -- reading well-written commentary from people far more accomplished than I. I lurked, because I couldn't contribute at the level that most of the regular commentors could, but I learned a great deal. HN has retained its preoccupation with not being reddit (which is noble), but has not retained the quality to justify it. Great communities are transient, and HN is probably what taught me that. I have nothing but respect for pg, and for the community that once populated HN. Peace. I'm out. Crazy rant done.
- 5hoom 15y agoYour finding the articles less interesting could be a function of you becoming more knowledgable yourself, therefore there is less "low hanging fruit" with regards to new knowledge for you to acquire. Might be a sign that it's time for you to start posting some well-writen commentary yourself ;)
- djcapelis 15y agoDude mkelly has known why a[5] and 5[a] were the same damn thing since before there was an HN. Stop making bad assumptions, he's telling a true story. I'm sorry to see him leave just as I realized he was here. Oh well. He's not the only one saying these things. It's just how it is. After awhile, what was is no more. HN stood longer than most.
- djcapelis 15y agoI'm sorry, but I'm happy to get voted down for my tone for once. I remember a time when one could assume that people around HN had a basic CS education and the community didn't get fascinated by stack overflow threads about how C works because we were all thinking about crazy interesting things. I think anyone who says that people don't have a right to miss that and assumes that there is no problem is part of the problem.
- mkelly 15y ago
- biot 15y agoTrying to intuit how a language works tends to be problematic. To understand this operation, you need to look it up in the spec: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf Section 6.5.2.1 "Array Subscripting" states in item (2) under "Semantics" on page 70: 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). In other words: a[5] is equal to (*((a)+(5))) 5[a] is equal to (*((5)+(a))) So what are the rules for E1+E2? Refer to section 6.5.6 "Additive Operators", item (8) under "Semantics" on page 83: When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. In other words, if (P)+N is equal to N+(P), you need only substitute "a" for "P" and "5" for "N" and that proves a[5] == 5[a]. If I've missed something, corrections are welcomed.
- deleted 15y ago[deleted]
- Someone 15y agoGiven that these are separate sections in the C spec, would &12[5] == 17 (ignoring OS memory protection)?
- biot 15y agoThe constraints section of 6.5.2.1 requires that one expression be a pointer. If you cast one of those numbers to a byte pointer with its address at the numerical location in memory, I don't see why it wouldn't result in a pointer to memory location 0x00000017. Give it a shot!
- kqueue 15y agoC 101.. HN is becoming sillier every day.
- tzs 15y agoIt's more amusing for multi-dimensional arrays: a[x][y] = y[x[a]] a[x][y][z] = z[y[x[a]]] and so on.
- bnegreve 15y agoOk, the "interesting" thing is this expression is that 5 is accepted as a variable identifier although it does not meet the requirements to be one. The fact that the expression evaluate to a result that turns to be correct is not so relevant.
- lurker19 15y agoI think you mean "pointer type", not "variable". 0xblah could very well a be valid pointer value. Anyway, Array subscripting (brackets) is not an operator in C. It is just syntactic sugar. This is different from C++ (but even in C++, C compatibility is maintained for primitives) .
- jc-denton 15y agoOld! C programmers know how this is expanded.
- program 15y agoI've read this example first time in a storic stackoverflow topic: http://stackoverflow.com/questions/1995113/strangest-language-feature http://stackoverflow.com/questions/1995113/strangest-languag... it will stay forever in my bookmarks.