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
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
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.
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.
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>
char _assert_wchar_t_is_16bit[ sizeof(wchar_t) == 2 ? 1 : -1];
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]