Suppose I wish to write a C program (C99 or C2011) that I want to be completely portable and not tied to a particular architecture.
It seems that I would then want to make a clean break from the old integer types (int
, long
, short
) and friends and use only int8_t
, uint8_t
, int32_t
and so on (perhaps using the the least
and fast
versions as well).
What then is the return type of main
? Or must we strick with int
? Is it required by the standard to be int
?
GCC-4.2 allows me to write
#include <stdint.h>
#include <stdio.h>
int32_t main() {
printf("Hello\n");
return 0;
}
but I cannot use uint32_t
or even int8_t
because then I get
hello.c:3: warning: return type of ‘main’ is not ‘int’
This is because of a typedef, no doubt. It seems this is one case where we are stuck with having to use the unspecified size types, since it's not truly portable unless we leave the return type up to the target architecture. Is this interpretation correct? It seems odd to have "just one" plain old int
in the code base but I am happy to be pragmatic.
Suppose I wish to write a C program (C99 or C2011) that I want to be completely portable and not tied to a particular architecture.
It seems that I would then want to make a clean break from the old integer types (int, long, short) and friends and use only int8_t, uint8_t, int32_t and so on (perhaps using the the least and fast versions as well).
These two affirmations, in bold, are contradictory. That's because whether uint32_t
, uint8_t
and al are available or not is actually implementation-defined (C11, 7.20.1.1/3: Exact-width integer types).
If you want your program to be truly portable, you must use the built-in types (int
, long
, etc.) and stick to the minimum ranges defined in the C standard (i.e.: C11, 5.2.4.2.1: Sizes of integer types),
Per example, the standard says that both short
and int
should range from at least -32767 to at least 32767. So if you want to store a bigger or lesser value, say 42000, you'd use a long
instead.
The return type of main
is required by the Standard to be int
in C89, C99 and in C11.
Now the exact-width integer types are alias to integer types. So if you use the right alias for int
it will still be valid.
For example:
int32_t main(void)
if int32_t
is a typedef to int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With