T
Tomás Ó hÉilidhe
I commonly use pointers to iterate thru an array. For example:
int my_array[X];
int *p = my_array;
int const *const pend = my_array + sizeof my_array/sizeof*my_array;
do *p++ = 42;
while (pend != p);
(Yes I realise the lack of spaces in the sizeof thing above is
disgusting, but I've gotten so sick of writing it out that I make it as
compact as possible)
I can't count how many times I use this construct in my code every day.
It's a right pain in the ass to always have to write out the long-winded
intialiser for pend, so I'm considering switching to initialising pend
as follows:
int const *const pend = *(&my_array+1);
1) my_array is an int[X]
2) &my_array is an int(*)[X]
3) &my_array+1 is the address of the non-existant array located after
the current one.
4) *(&my_array+ 1) decays to the address of the first element in the
non-existant array after the current one, which is also the "pend"
address for the array that actually exists.
It's a hell of a lot shorter to write, and also I think it's a little
less vulnerable to typos because you'll most likely get a type mismatch
if its written wrongly.
Anyway, just wondering what people think of the alternative. Saves me
that little rush of pissed-off-ness every time I've to write out the
tedious sizeof thing.
(Oh and by the way, I wouldn't use a macro such as ARRLEN(my_array)
because then I'd have to worry about including the necessary header
file... which is also the reason why I don't use NULL.)
int my_array[X];
int *p = my_array;
int const *const pend = my_array + sizeof my_array/sizeof*my_array;
do *p++ = 42;
while (pend != p);
(Yes I realise the lack of spaces in the sizeof thing above is
disgusting, but I've gotten so sick of writing it out that I make it as
compact as possible)
I can't count how many times I use this construct in my code every day.
It's a right pain in the ass to always have to write out the long-winded
intialiser for pend, so I'm considering switching to initialising pend
as follows:
int const *const pend = *(&my_array+1);
1) my_array is an int[X]
2) &my_array is an int(*)[X]
3) &my_array+1 is the address of the non-existant array located after
the current one.
4) *(&my_array+ 1) decays to the address of the first element in the
non-existant array after the current one, which is also the "pend"
address for the array that actually exists.
It's a hell of a lot shorter to write, and also I think it's a little
less vulnerable to typos because you'll most likely get a type mismatch
if its written wrongly.
Anyway, just wondering what people think of the alternative. Saves me
that little rush of pissed-off-ness every time I've to write out the
tedious sizeof thing.
(Oh and by the way, I wouldn't use a macro such as ARRLEN(my_array)
because then I'd have to worry about including the necessary header
file... which is also the reason why I don't use NULL.)