Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time assert on datatype sizes

I would like to perform a compile-time check on datatype sizes in a C/C++ project, and error on unexpected mismatches. Simple

#if sizeof foo_t != sizeof bar_t

does not compile - claims that sizeof is not a proper compile-time constant.

The desired scope of platforms - at the very least Visual C++ with Win32/64, and GCC on x86/amd64.

EDIT: compile-time, not necessarily preprocessor. Just not a run-time error.

EDIT2: the code assumes that wchar_t is 2 bytes. I want a compilation error if it's accidentally compiled with 4-byte wchar's.

like image 207
Seva Alekseyev Avatar asked Dec 05 '11 16:12

Seva Alekseyev


People also ask

Are asserts evaluated at compile time?

assert(f != must be done at run time. However, an assertion that tests the value of a constant expression, such as the size or offset of a structure member, can be done at compile time.

Is static assert compile time?

Of course, the expression in static assertion has to be a compile-time constant. It can't be a run-time value.

Is assert a runtime?

A runtime assertion is a statement that is expected to always be true at the point in the code it appears at. They are tested using PHP's internal assert() statement. If an assertion is ever FALSE it indicates an error in the code or in module or theme configuration files.


1 Answers

in C++11 you can use static assert

static_assert(sizeof(foo_t) == sizeof(bar_t), "sizes do not match");

If it is pre C++11 then you can use boost static assert macro

http://www.boost.org/doc/libs/1_48_0/doc/html/boost_staticassert.html

BOOST_STATIC_ASSERT(sizeof(int)==sizeof(unsigned));
BOOST_STATIC_ASSERT_MSG(sizeof(int)==sizeof(unsigned), "sizes do not match");
like image 56
111111 Avatar answered Nov 15 '22 21:11

111111