4 ms·
Given how many bugs & errors stem from simple fails in range checks etc, I would much rather go with the tried and true way rather than use something "clever".
by Etheryte 10y ago
Given how many bugs & errors stem from simple fails in range checks etc, I would much rather go with the tried and true way rather than use something "clever".
Quoting http://stackoverflow.com/a/16019052/1470607 http://stackoverflow.com/a/16019052/1470607
Note that this trick will only work in places where `sizeof` would have worked anyway.
- Animats 10y agoYes. This only works for arrays on the stack, at best. It assumes that arrays are placed on the stack in the order of declaration, which is not a requirement of the C standard and may differ between compilers. Unless you're writing a buffer overflow exploit, in which case you need to know exactly what's on the stack and where, this isn't a good way to program. Update: misread the article; thought he was differencing with the beginning of the next array.
- ycmbntrthrwaway 10y ago> It assumes that arrays are placed on the stack in the order of declaration I am not sure it is the case here. The code uses only one array, how can it assume the order of arrays?
- dllthomas 10y agoI don't see how the code assumes anything about the placement of the array. Indeed, it works just fine for static arrays: $ cat test.c #include <stdio.h> int arr[5]; int main(int argc, char *argv[]) { printf("%lu, %ld\n", sizeof(arr) / sizeof(*arr), (&arr)[1] - arr); } $ gcc test.c && ./a.out 5, 5 Not saying it's "a good way to program" - it's needlessly obfuscated compared to the standard sizeof alternative. But it doesn't rely on anything tricky.