Alex Rivera | Logout

Compile-time assert on datatype sizes

Asked 2011-12-05T16:23:44.217
14

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.

Edit
Report

2 Answers

4

You could define a compile time assert macro like this:

#define COMPILE_TIME_ASSERT( x ) \
  switch ( x ) \
  { \
  case false: \
    break; \
  case ( x ): \
    break; \
  }

If the expression is false, you will get a duplicate case label error.

answered 2012-01-19T14:48:29.373
3

If you can't use C++11 or Boost, then you might find this useful:

template <typename A, typename B>
struct MustBeSameSize {
    int c[sizeof(A)-sizeof(B)];
    int d[sizeof(B)-sizeof(A)];
};
template struct MustBeSameSize<int, int>;

That will only compile if and only if the sizeof the two types is identical. If they are different like this:

template struct MustBeSameSize<char, int>;

then you'll get a compile-type error, but it won't be a very readable error; maybe something like (g++ 4.4.3):

error: overflow in array dimension

This works because any modern compiler should allow zero-length arrays, but not negative-length arrays.

This works for me, and I think G++ has allowed zero-length arrays for some time. But I'm not sure how portable this is. C99 allows flexible array members (i.e. unspecified size), but I don't think that's directly relevant. In short, if you need something portable, use C++11 or use Boost.

answered 2011-12-05T20:43:02.540

Your Answer