views:

146

answers:

3

Consider:

int a[2] = {0,1};
int *address_of_second = (&a[1]);

I assume this works because it's translated to &*(a+1) and then the & and * cancel each other out, but can I count on it, or is it compiler-specific? That is, does the C standard have anything to say about this?

Is this a decent way to write? Personally I think that writing:

int *address_of_second = a+1

is better, do you agree?

Thanks.

+8  A: 

You can count on the behaviour in your first code example.

I assume it works because it's translated to &*(a+1) and then the & and * cancel each other, but can I count on it, or is it compiler specific? that is, does the standard have any thing to say about this?

a[1] is the same as *(a + 1), and &a[1] is the same as &(*(a + 1)), which gives you a pointer (&) to the (dereferenced, *) int at a + 1. This is well-defined behaviour, which you can count on.

int *address_of_second = a+1

This is readable, but not quite as readable as &a[1] in my opinion. &a[1] explicitly shows that a is a pointer, that you're referencing an offset of that pointer, and that you're getting a pointer to that offset. a + 1 is slightly more ambiguous in that the actual line doesn't tell you anything about what a is (you can deduce that it's a pointer but for all you know from that snippet a could be just an int).

Even so, that's just my opinion. You're free to make up your own style decisions, so long as you understand that behind the scenes that they're the same at the lowest level.

Matthew Iselin
GrahamS
+1  A: 

it is a matter of style, or code convention if you work in a group. Both forms are c++ compatible on all conforming compilers.

I prefer the former :)

vehomzzz
+1  A: 

Both work. My personal preference would be either &(a[1]) or a+1. I prefer the bracket placement in the first because it makes it very clear what I'm taking the address of. I'd tend to use that in most situations. If the code in question is doing a lot of pointer arithmetic, then I might use the second form.

Jon Bright