Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf performing implicit casting

In the below code snippet, why do we get an output of 600? Two questions will help me understand the behavior.

  1. I specified the type for variable b to be uint8_t, why doesn't the math operation restrict to the same type?
  2. I thought PRIu8 is the right type to print uint8_t, why isn't this working?

I was hoping to get the answer 88 which results from looping beyond the range of uint8_t

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

void main()
{

    uint8_t b = 200;
    printf("%" PRIu8 "\n",b+b+b);
    printf("%" PRIu8 "\n",3*b);

}

gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1)

like image 296
niil87 Avatar asked Mar 09 '26 18:03

niil87


1 Answers

In my opinion it is a library bug.

In MS Visual Studio the macro PRIu8 is expanded to hhu as it should be and you get the expected result.

It is interesting to note that if to use clang then if you will write for example

printf("%" PRIu8 "\n",( uint8_t)(b+b+b));

when again you will get the expected result.

like image 185
Vlad from Moscow Avatar answered Mar 11 '26 07:03

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!