Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an address using both square brackets and ampersand

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.

like image 986
Liran Orevi Avatar asked Dec 22 '22 09:12

Liran Orevi


2 Answers

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.

like image 155
Matthew Iselin Avatar answered Jan 05 '23 00:01

Matthew Iselin


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 :)

like image 33
vehomzzz Avatar answered Jan 04 '23 23:01

vehomzzz