When should we use integer types defined in stdint.h?

stdint.h defines integer types with the specified width. When should we use these types, for example uint32_t instead of unsigned int ? Is it because we can get the types we want without considering the underlying machine?

+4
source share
3 answers

When you need to communicate with other systems, and you want to be sure of the length of the data.

For example: you save your number to disk. What is the time on a disk? With unsigned int answer is "compiler dependent, OS ...". With uint32_t this is 32 bits (4 bytes on "standard" architectures).

+4
source

When the size and signature of an integer is really important. Imagine you have a file or socket that provides uint32_t values ​​and you want to read it (in a portable way). Reading only unsigned int values ​​may be correct, but it can also be terribly wrong.

+3
source

Using <stdint.h> (or creating your own surrogate) is very common in embedded development. This makes variable sizes and memory usage more obvious and greatly simplifies porting. I find myself using <stdint.h> when writing desktop software in C when I'm used to it from embedded development. The thought of the magnitude of the variables also makes me think of cases of overflow, etc.

For me, this will simply clear C to use the <stdint.h> -defined types, since it makes everything much more portable and the source code more explicit in its stack / heap allocation. Accepted, this makes more sense in memory-limited systems, but I still think it's good practice.

0
source

Source: https://habr.com/ru/post/1401319/


All Articles