Integer types in C

Suppose I want to write a C program (C99 or C2011) that I want to fully port and not bind to a specific architecture.

It seems like I would like to make a clean break with the old integer types ( int , long , short ) and friends and use only int8_t , uint8_t , int32_t and (possibly using the least and fast versions).

What is the main return type? Or should we stream with int ? Is a standard int value required?

GCC-4.2 allows me to write

 #include <stdint.h> #include <stdio.h> int32_t main() { printf("Hello\n"); return 0; } 

but i can't use uint32_t or even int8_t because then i get

 hello.c:3: warning: return type of 'main' is not 'int' 

This is due to typedef, no doubt. This seems to be one case where we are stuck with unspecified size types, since it is not really portable unless we leave the return type to the target architecture. Is this interpretation correct? It seems strange to have “only one” simple old int in the code base, but I'm happy to be pragmatic.

+4
source share
2 answers

Suppose I want to write a C program (C99 or C2011) in which I want to be fully portable and not tied to a specific architecture.

It seems that I would like to take a clean break from the old integer types (int, long, short) and friends and use only int8_t, uint8_t, int32_t, etc. (possibly using the smallest and fastest versions).

The two statements in bold are contradictory. This is because whether uint32_t , uint8_t and al are available or not, it is actually determined by the implementation (C11, 7.20.1.1/3: integers with maximum length).

If you want your program to be truly portable, you must use the built-in types ( int , long , etc.) and adhere to the minimum ranges defined in the C standard (for example: C11, 5.2.4.2.1: Dimensions of integer types) ,

For example, the standard states that both short and int should have a range from at least -32767 to at least 32767. Therefore, if you want to keep a larger or smaller value, say 42000, you should use long .

+9
source

The return type of main requires the standard to be int in C89, C99, and C11.

Now integer types of exact width are aliases for integer types. Therefore, if you use the correct alias for int , it will still be valid.

For instance:

 int32_t main(void) 

if int32_t is typedef before int .

+6
source

All Articles