I just read an excellent post, Portable Fixed-Width Integers in C, everything makes perfect sense till the almost the end, I am wondering what does the following paragraph means:
Of course, if you don’t have a C99-compliant compiler yet you’ll still have to write your own set of typedefs, using compiler-specific knowledge of the char, short, and long primitive widths. I recommend putting these typedefs in a header file of your own design and adding the anonymous union declaration shown in Listing 2 to a linked source module to check their sizes; that is, to gently “remind” whomever might someday have the task of porting your code.
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];
};
Listing 2. This anonymous union allows a compiler to detect and report typedef errors
I experimented a small program:
typedef unsigned char int8_t;
typedef unsigned short int16_t;
union u {
char int8_incorrect[sizeof(int8_t)==1];
char int16_incorrect[sizeof(int16_t)==2];
};
int main() {
return 0;
}
There is no issue going through compiler. I changed int8_t into the following:
typedef unsigned int int8_t;
There is no issue either.
Basically I missed the point why this example code can detect error.
Could you clarify what I missed?
If you compile with
gccadd-std=c89 -pedanticor-std=c99 pedanticto yourgcccompile options to get the warning with this typedef and the union type:For this typedef:
it is normal you don’t get any warning, as the trick is to check the size of type, not wether it is a signed or unsigned type.