0

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]

I've come across the following code in my C book and I'm perplexed as to when you would ever use it:

int doses[] = {1, 2, 3, 1000};
printf("Issue dose %i", 3[doses]); 

I'd only ever used: doses[3], and never seen 3[doses].

What is this type of array called, and when would you use it?

(I compiled it and it's perfectly valid C syntax, it returns "Issue dose 1000" as expected)

Community
  • 1
  • 1
ben
  • 321
  • 4
  • 12
  • 1
    Question closed as a duplicate... so somewhere on StackOverflow somebody has asked this question, and an answer exists as to the name of the array type and when it would be used, but we'll never now where. It's a duplicate, but since I don't know the name of the array, and therefore what to search for, I'll never know! – ben Jan 20 '13 at 03:48
  • You would never use it (barring the joy of keeping your coworkers scratching their heads and cursing your name). Regarding the 'type' of the array, its right there in your code; `int`. There is nothing special or unique about this, it is just a compiler nuance that treats a[b] as *(a+b) so long as one is an address/pointer type, and one is an integer type. – WhozCraig Jan 20 '13 at 03:57
  • 1
    @ben, it is closed as a duplicate for an entry that is found in the FAQ. Did you scan through the FAQ first? – Jens Gustedt Jan 20 '13 at 07:47

1 Answers1

3

a[b] roughly translates to *(a+b). Usually the pointer (in this case, the name of an array) comes first, but it is not necessary.

Maciej Stachowski
  • 1,708
  • 10
  • 19
  • Thanks, but the question is when would somebody use this syntax? I can't see any inherent advantage, and everybody is so quick to close the question I guess I never will. – ben Jan 20 '13 at 03:52
  • 1
    @ben there is no advantage of using other one in place of other one, its just flexibility which you can use freely. Use the one which you feel readable – exexzian Jan 20 '13 at 03:54
  • Thanks very much sansix. Everybody was so quick to close the question because the part about the syntax being valid has come up before. You're the first person to answer the actual questioN! – ben Jan 20 '13 at 03:55
  • Hopefully nowhere ;) It's just a little quirk, probably unintended by the language creators. Check out the link at the top of your question, there's a nice discussion and a couple of reasons for why this works. – Maciej Stachowski Jan 20 '13 at 03:58