Hacker News new | past | comments | ask | show | jobs | submit login
a[5] == 5[a] (stackoverflow.com)
21 points by stephth on Aug 11, 2011 | hide | past | favorite | 36 comments



Warning: 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.


To be honest, I feel the same way, but maybe there's a good explanation for the relative decline of "quality".

I think I started lurking HN back in 2007 (which I also believe is the first year of HN). I remember feeling a euphoric sense of being overwhelmed with great content from knowledgeable people and articles. I learned a lot about start ups. I learned a lot about programming. I learned a lot about partaking and consuming thoughtful commentary in a semi-anonymous setting.

But you know what? All of that content is still here, in different formats. The audience is bigger and so there tends to be more mainstream stuff on HN now, particularly around politics. But I think the biggest change is in myself. I've read the same stuff about lean startups at least 100 times now rehashed in different ways. Even though I've never raised money from a VC before, every time I read something on HN about it, I feel like I've been through the process dozens of times. Every 37signals blog post that gets submitted seems like a rehash of the last one. So most of the submitted content around those topics seem like old-hat.

At some point, when you continue to consume the content from the same sources for years on end, you're going to see more repeat episodes and you'll have fewer stimulating moments. That's just the nature of it - and I think it's just as important to recognize that we're transient individuals. Your probably a different person now with a higher capacity and understanding and that's probably in part thanks to HN.


Your 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 ;)


Dude 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.


I'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.


This is a very good point.

I'm this is true to some extent, but (as much as I'd love to wholeheartedly agree with you), the reason I don't consider this likely is this: the main reason I have this opinion of HN is because of one 3-month period in 2009, where I was off the grid (bought a car in Europe, drove around, drank lots of booze, smoked some mushrooms, &c). I assure you I didn't learn about computers during that time. When I left in June, I thought HN was full of insightful articles and comments; when I returned in September, I thought it was markedly worse. I think HN had its Eternal September then, and it's been steadily downhill since then.

(Um, yes, I was keeping track of replies, and logged back in to post this. Mea culpa.)


My apologies if my post sounded disrespectful in any way though.

I wrote my post from the perspective of being a long time lurker on various tech forums who is only just beginning to feel I may be able to contribute on some topics (and only after many years of coding, reading & sponge-learning from sites like this one).

If it weren't for stories like this & people like yourself engaged in insightful discussion about them I personally would have missed a lot of "assumed knowledge" in the developer world, heck I wouldn't have heard of K&R (the shame!).

So I guess what I'm saying is: please don't leave, stay & help make us noobs less ignorant!

[edit] context


I think that it's general knowledge that a[x] is a + (x * sizeof a). The idea that a[x] could be reversed to x[a] is probably not common knowledge though. I don't necessarily think that a[x] = x[a] would be "C 101." I've certainly never come across any C code that uses this property and I can't really think think of any good uses for this property that don't end up ruining the readability of the code. And in general, it seems a rather useless property that, as others have stated, is just a side-effect.

I could just as easily claim that HN has 'degenerated' if someone posts a Stack Overflow post about what the /o flag does on Perl regexes. Or maybe there will be a Stack Overflow post about how substr('abc', 1, 1) == substr('abc', 0, 1) in Oracle because it helpfully translates the 0 index to a 1 index. I mean, it's right here in the Oracle docs[1]:

  When position is 0 (zero), then it is treated as 1.
It's Oracle 101!

[1] http://download.oracle.com/docs/cd/B28359_01/olap.111/b28126...


Trying 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

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.


Given that these are separate sections in the C spec, would

  &12[5] == 17
(ignoring OS memory protection)?


The 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!


I 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.


You'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.


Interesting 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.


I 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.


It 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.


Every language has idiosyncrasies. IMO it's tough to use a language effectively without knowing them, even if you don't use them. I mean, imagine trying to use Ruby and not knowing about implicit return values. Or the obscure array slice operations in Python. Every language has its own funky things.


I agree. I posted a crazy rant elsewhere in the comments, actually, prompted by the same thoughts.

Poor HN.


That 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.


As noted in the SO comments: when compiling the "+", the compiler uses the sizeof of the referenced type of whichever addend is actually a pointer.


I 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.


This 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?


I 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.


To 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.


It works if you think of it as expanding to *(a + 5). Pointer addition is defined to be scaled by the size of the pointer.


No; 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.


Don't forget the dereference -

    *((pointer-type)(e*sizeof(*p) + (size_t)p))
    *((pointer-type)((size_t)p + e*sizeof(*p)))


Again, no: I was talking about the separate overloading of the addition operator when applied to an integer type and a pointer type.


[deleted]


That 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.


It 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.


It's more amusing for multi-dimensional arrays:

   a[x][y] = y[x[a]]
   a[x][y][z] = z[y[x[a]]]
and so on.


C 101.. HN is becoming sillier every day.


Ok, 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.


I 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) .


I've read this example first time in a storic stackoverflow topic:

http://stackoverflow.com/questions/1995113/strangest-languag...

it will stay forever in my bookmarks.


Old! C programmers know how this is expanded.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: