Why is the format specifier for uint8_t and uint16_t the same (% u)?

I found rather unrelated questions due to the large number of printf() search results.

Why uint8_t n't uint8_t indicate its own format string, but does any other type do?

As far as I understand printf() , it should know the length of the provided parameters in order to be able to parse the list of variable arguments.

Since uint8_t and uint16_t use the same %u format specifier, how does printf() β€œknow” how many bytes to process? Or is there some kind of implicit cast to uint16_t involved in the delivery of uint8_t ?

Perhaps I am missing something obvious.

+5
source share
2 answers

printf() is a variational function. His optional arguments (and only those) are encouraged by default promotions (6.5.2.2. P6).

Since you are asking for integers, in this case, whole promotions apply, and the types you mention get up to int . (rather than unsigned int because C)

If you use "%u" in printf () and pass it the uint16_t variable, then the function converts it to int and then to unsigned int (because you requested it with% u) and then prints it.

+4
source

Since% u means "unsigned", it may be uint64_t and is architecture dependent. According to man 3 printf , you can use the length modifier to look for distorted behavior, i.e.% hu (uint16_t) and% hhu (uint8_t).

+5
source

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


All Articles