I want to compile a time error checking as mentioned below . But I am not able to find out how to use it inside main()?
#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
#define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); }))
int main(){
BUILD_BUG_ON_NULL(12);
}
Below is the mentioned error
1--error C2332: 'struct' : missing tag name
2--error C2143: syntax error : missing ')' before '{'
3--error C2027: use of undefined type 'main::<unnamed-tag>'
4--error C2143: syntax error : missing ';' before '{'
5--error C2059: syntax error : ')'
Can anyone please let me know what I am doing wrong?
First the macros
BUILD_BUG_ON_ZEROandBUILD_BUG_ON_NULLtrigger a compilation error if their argument is different than0.If the macro argument is
0, they will not trigger any compilation error but yield a0forBUILD_BUG_ON_ZEROand a(void *) 0forBUILD_BUG_ON_NULLThese macros comes from the Linux kernel which is written in C and they are only working for C programs.
In C++ these macros are not working. The reason is in C++ you cannot declare a structure in a
sizeofexpression.You don’t mention in your question if you are compiling your program in C or in C++, but I strongly suspect you are compiling it in C++. So don’t use these macros in C++.