Detect and Report typedef Errors... What's This Doing?
I was reading about making code more portable 开发者_StackOverflow社区by using fixed-width integers. I found this article which helped explain things, and at the end it suggests using this anonymous union to detect and report typedef errors:
static union
{
char int8_t_incorrect[sizeof( int8_t) == 1];
char uint8_t_incorrect[sizeof( uint8_t) == 1];
char int16_t_incorrect[sizeof( int16_t) == 2];
char uint16_t_incorrect[sizeof(uint16_t) == 2];
char int32_t_incorrect[sizeof( int32_t) == 4];
char uint32_t_incorrect[sizeof(uint32_t) == 4];
};
I'm a little lost and I was hoping someone could explain what this is doing?
It's abusing the compiler, that's what it's doing.
Basically the sizeof(type) == num
is being evaluated at compile time, and it's going to produce either a 0
or a 1
(false or true). If it's 0 (which none of them should be), it produces a compiler error, since you can't declare an array of size zero.
But as mentioned, this is quite abusive of the compiler, and most sane build environments would ensure the typedefs are correct for you (autoconf for example has built-in macros for this kind of stuff).
If any of those equality checks result in false that union will have a field with an array size of 0, which isn't allowed and will result in a compiler error.
精彩评论