C Programming Basics
In embedded programs, variables that hold the value of a 32-bit peripheral register are often declared with uint32_t from stdint.h rather than unsigned int. Which of the following is the main reason?
- Auint32_t does not wrap to 0 when a value exceeds the maximum but stops at the maximum (saturates)
- BReads and writes of a variable declared as uint32_t are no longer removed by compiler optimization
- CThe size of unsigned int differs between implementations, whereas uint32_t is defined as an unsigned integer of exactly 32 bits
Show answer and explanation
Answer: C. The size of unsigned int differs between implementations, whereas uint32_t is defined as an unsigned integer of exactly 32 bits
uint8_t, uint16_t, uint32_t, int32_t and the like from stdint.h are integer types whose bit widths are fixed as their names say (exact-width integer types). unsigned int may be 16 or 32 bits, so using exact-width types where the width must match a register or where a communication data format is defined keeps the meaning unchanged when the code moves to another CPU. Like other unsigned integer types, uint32_t wraps to the remainder modulo 2³² when it overflows. To keep reads and writes from being removed, volatile is added separately from the type.
- A. Unsigned integer types wrap back toward 0 on overflow. To stop at the maximum, saturation must be written explicitly.
- B. Keeping reads and writes from being removed is the job of volatile and has nothing to do with the type uint32_t.
- C. Correct. It is handled at the same 32-bit width in every implementation.