|
|
|
|
|
by kazinator
2655 days ago
|
|
> good old C has uint16_t Firstly, no, good old C doesn't. These things are a rather new addition (C99). In 1999 there was decades of good old C already which didn't have int16_t. It is implementation-defined whether there is an int16_t; so C doesn't really have int16_t in the sense that it has int. > It's funny because C opted to leave the number of bits machine dependent in the name of portability, but that turns out to have the opposite effect. Is that so? This code will work nicely on an ancient Unix box with 16 bit int, or on a machine with 32 or even 64 bit int: #include <stdio.h>
int main(void)
{
int i;
char a[] = "abc";
for (i = 0; i < sizeof a; i++)
putchar(a[i]);
putchar('\n');
return 0;
}
Write a convincing argument that we should change both ints here to int32_t or whatever for improved portability. |
|
Yes, it does. The C99 standard has been around for 20 years. I started giving up on compilers that don't support it 10 years ago. I consider it a given for C.
>> It is implementation-defined whether there is an int16_t
No, it's not. That type is part of the C99 standard.
>> Is that so? This code will work nicely on an ancient Unix box with 16 bit int, or on a machine with 32 or even 64 bit int:
That's cool, your example only needs to count to 3. Any size integer will do. The problems arise when you go to 100,000 and that old 16bit machine rolls over at 65536 but the newer ones don't. Other times someone (me) may want things to roll over at the 16 bit boundary and we need to specify the size as int16_t rather than figure out if int or short or char is that size for each architecture. (and yes I know rollover is undefined behavior)
>> Write a convincing argument that we should change both ints here to int32_t or whatever for improved portability.
In your example it doesn't matter. I'd argue that at least giving the size of your integers some thought every time is a good habit to get into so you don't write non-portable code in the cases where it does matter. You are free to argue that it's too much effort or something, but I'd invite you to argue that "i16" is more effort to type than "int".