tags:

views:

681

answers:

6

Is there some way to do something like this in c++, it seems sizeof cant be used there for some reason?

#if sizeof(wchar_t) != 2
#error "wchar_t is expected to be a 16 bit type."
#endif
+12  A: 

No, this can't be done because all macro expansion (#... things) is done in the pre-processor step which does not know anything about the types of the C++ code and even does not need to know anything about the language! It just expands/checks the #... things and nothing else!

There are some other common errors, for example:

enum XY
{
  MY_CONST = 7,
};

#if MY_CONST == 7
  // This code will NEVER be compiled because the pre-processor does not know anything about your enum!
#endif //

You can only access and use things in #if that are defined via command line options to the compiler or via #define.

rstevens
+2  A: 

sizeof() is a runtime compile-time function. You cannot call that in a preprocessor directive. I don't think you can check the size of wchar_t during preprocessing. (see Edit 2)

Edit: As pointed out in comments, sizeof() is mostly calculated at compile time. In C99, it can be used at runtime for arrays.

Edit 2: You can do asserts at build time using the techniques described in this thread.

nagul
sizeof() is NOT a runtime function. It is a compile-time expression that is evaluated by the compiler on compile-time (but after pre-processor time).
rstevens
Thanks, wasn't aware of that. Updated accordingly.
nagul
@nagul: Okay, maybe not always a compile-time expression :-)
rstevens
+5  A: 

The preprocessor works without knowing anything about the types, even the builtin one.

BTW, you can still do the check using a static_assert like feature (boost has one for instance, C++0X will have one).

Edit: C99 and C++0X have also WCHAR_MIN and WCHAR_MAX macros in <stdint.h>

AProgrammer
+3  A: 

I think things like BOOST_STATIC_ASSERT could help.

EFraim
+1  A: 
char _assert_wchar_t_is_16bit[ sizeof(wchar_t) == 2 ? 1 : -1];
Adrian Panasiuk
+2  A: 

Wouldn't you get basically what you want (compile error w/o the fancy message) by using a C_ASSERT?

#define C_ASSERT(e) typedef char __C_ASSERT__[(e)?1:-1]
gatorfax