Re:Pitfalls in C and C++: Unsigned Types (2011)
by dllthomas on Wednesday September 25, 2013 @03:05PM
(#6446603)
The fact that we're talking about C doesn't really make a difference, if you genuinely desire negative indices:
[ Parent
| on HN ]
Re:Pitfalls in C and C++: Unsigned Types (2011)
by cgore on Wednesday September 25, 2013 @03:11PM
(#6446638)
That's actually a nice trick. I just hope the compiler doesn't complain about it. I'll have to try that sometime.
EDIT: just tried it. The following works:
#include <stdio.h>
int main(void)
{
int array[100];
int *shifted_array = array - 1980;
for (int i = 0; i < 100; i++)
array[i] = i;
for (int j = 1980; j < 2014; j++)
printf("shifted_array[%d] = %d\n", j, shifted_array[j]);
return 0;
}
Re:Pitfalls in C and C++: Unsigned Types (2011)
by dllthomas on Wednesday September 25, 2013 @03:44PM
(#6446837)
Yeah, there's a couple cases where this kind if thing cleans things up; use it with caution though.
More amusing, but less useful outside the IOCCC:
The C subscripting operator performs an basically syntactic transformation, turning a[i] into (*(a + i)). This means that, counter-intuitively (if you're thinking of [] as a lookup) the construct i[a] works too because plus is commutative.