Reputation: 3245
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?
Upvotes: 1
Views: 128
Reputation: 30465
My understanding is that arrays of length 0 are disallowed by the C standard. If you write sizeof(int8_t) == 1
as the array length, and sizeof(int8_t)
is not 1, the comparison will evaluate to 0, and you will have an illegal array size.
However, the following link shows that GCC does allow zero-length arrays:
http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
...so if you are using GCC, that might be the reason you didn't get an error.
Upvotes: 0
Reputation: 145899
If you compile with gcc
add -std=c89 -pedantic
or -std=c99 pedantic
to your gcc
compile options to get the warning with this typedef and the union type:
typedef unsigned int int8_t;
For this typedef:
typedef unsigned char int8_t;
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.
Upvotes: 1