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.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With