c++ - The macro `assert`, why doesn't it compile in the global scope? -
this snippet in cppreference doesn't compile. understand problem has fact assert
macro expanded in global scope. is, if include part of code below, starting assert(sieof(s)==8);
inside function, main()
example, code work.
#include <cassert> struct s { char c; // 1 byte value // 3 bytes padding float f; // 4 bytes value bool operator==(const s& arg) const { // value-based equality return c == arg.c && f == arg.f; } }; assert(sizeof(s) == 8); s s1 = {'a', 3.14}; s s2 = s1; reinterpret_cast<char*>(&s1)[2] = 'b'; // change 2nd byte assert(s1 == s2); // value did not change
but want understand why code doesn't compile, stated in original code. example in vs2013, macro defined follows:
#define assert(_expression) (void)( (!!(_expression)) || (_wassert(_crt_wide(#_expression), _crt_wide(__file__), __line__), 0) )
and compiler complains following error message:
error c2062: type 'void' unexpected
the obvious question is: why void
accepted inside main
not in global scope?
see error messages in clang.
global scope can contain declarations. assert macro expands expression statement, cannot appear @ global scope.
Comments
Post a Comment