-
Notifications
You must be signed in to change notification settings - Fork 550
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Safer NK_LEN macro #467
base: master
Are you sure you want to change the base?
Safer NK_LEN macro #467
Conversation
C++ sizeof will never return 0. From C++ standard, 9/3 "Classes": "Complete objects and member subobjects of class type shall have nonzero size." |
IMHO if the new macro helps in some real cases or for some compilers, then we can merge this. Any such examples @ryuukk ? |
Neither will C. The lowest addressable unit is defined to be |
Sorry i didn't meant "and when used from C++" I meant when used with a <= C11 compiler, it'll refuse to compile |
Looks ok to me too Just missing |
Many C compilers support the zero length array extension. Although this is non-standard the following program will compile with no warnings with Clang/GCC and returns 0. #include <stdio.h>
int main(){
struct zbs { char test[0]; };
return sizeof(struct zbs);
} however the following will produce division by zero warnings #include <stdio.h>
#define NK_LEN(a) (sizeof(a)/sizeof(a)[0])
int main(){
struct zbs { char test[0]; };
struct zbs arr[3];
return NK_LEN(arr);
} Since most if not all demo backends compile with |
Protects from division by 0 and when used from <= C11
https://stackoverflow.com/a/1598827