Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect and Report typedef Errors... What's This Doing?

Tags:

c++

I was reading about making code more portable 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?

like image 922
Morgan Avatar asked Aug 11 '11 00:08

Morgan


2 Answers

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).

like image 108
Chris Eberle Avatar answered Oct 14 '22 03:10

Chris Eberle


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.

like image 42
Alex Avatar answered Oct 14 '22 02:10

Alex