The last example in this tutorial regarding Implicit type conversion states that std::cout << 5u - 10;
will produce 4294967291
rather than -5
due to type conversion. I tried this in both C and C++. The result in C++ was as promised, however when using C ( printf("%d\\n", 5u - 10);
) the result was -5
. What happened?
In the C example there is no type conversion whatsoever. C just evaluates the expression 5u - 10
and pushes the result onto the stack. Then printf sees a type character and interprets the value on the stack as such when printing it. The type character is d
( %d
) meaning "decimal integer" and hence the position on the stack is retrieved as an int and is printed as (signed) decimal.
Would the type character be for example ld
( %ld
), the position on the stack would be retrieved as a long, even if only an int was pushed, and that would be printed as a (signed) decimal number. Again, there is no type conversion whatsoever (there will just be a nonsense number printed).
A little more thought brought upon the realization that the problem was with the printf
rather than the conversion itself. Notice that what was written was printf("%d")
. This performed yet another conversion back to signed int
, which is why I saw the result of -5
.
When testing with printf("%u")
, the promised result ( 4294967291
) was shown.
To cap it off, printf("%X")
resulted in FFFFFFFB
which means both those values, depending on a signed or unsigned interpretation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.