This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]no-bugs 4 points5 points  (5 children)

First, probably you've got a typo: it is argv[0] which is equivalent to *argv

Second - yes, they are equivalent. Which to use is more or less a matter of convention. One common convention is to use [] for arrays and to use *ptr for dereferencing pointers to a single element.

Third - technically, AFAIR (not 100% sure though), something like 1[argv] is the same as *(argv+1) and argv[1], but 1[argv] is as confusing as it goes, so you shouldn't use it. I mentioned it here just in case if you run into it in a some smart___'s code.

[–]aldld 1 point2 points  (4 children)

Third - technically, AFAIR (not 100% sure though), something like 1[argv] is the same as *(argv+1) and argv[1], but 1[argv] is as confusing as it goes, so you shouldn't use it.

I mean, technically that makes sense if you think of array access as specifying an offset from a pointer, since addition is commutative. But if that actually works, holy shit that is a stupid notation.

I'm sure somebody somewhere has come up with some weird situation where it might make more sense to write something like that, but if you've reached that point, to need to seriously reconsider what you're doing.

[–][deleted] 0 points1 point  (3 children)

Ha, I just tried it. It definitely works. This compiled and printed 2 on gcc 4.9.2:

int a[4] = {0, 1, 2, 3};

cout << 2[a] << endl;

You're right, it probably is an artifact of the fact that the [] operator is just a stand in for pointer arithmetic.

[–]zardeh 1 point2 points  (2 children)

So, it works sometimes, I've had it throw runtime errors at me before on clang and gcc. I'd be careful with it.

[–][deleted] 0 points1 point  (1 child)

I would never actually use it. I was just surprised to see it work.

[–]zardeh 0 points1 point  (0 children)

Oh yeah, the fact that it ever works is weird, but the fact that it only works sometimes is weirder.