I have this question when I learn the source code of operator<<(ostream &,bool). I find that when outputing a bool value using cout, program always first casts bool to unsigned long, and then prints such unsigned long value. (See this article in Chinese) So what happened when doing such conversion? If a bool value b is -1, what will cout<<b<<endl display?
The amswer is: bool will be treated as unsigned value, be zero-extended to unsigned long, and then be output.
It spends me a lot of time thinking of why, but finally I find this is very obvious…
First, let’s figure out that: is bool an unsigned value? The answer is: Yes. The discussion in stackoverflow said this. And the discussion also claims that bool is integral type too.
Second, how program casts the narrower integral type data to wider integral type? The program will change the size of data first, and change the signedness. So, signed value is casted like being signed-extended, and unsigned value is casted like being zero-extended.
So, bool value is zero-extended to unsigned long.
We can see the assembly code to vertify this too:
1 | 0000000000000046 <_Z4tranbPm>: |
- 本文作者: ChrisLee
- 本文链接: https://ipchrislee.github.io/2022/03/04/What-happened-when-converting-bool-value-to-unsigned-long-type/
- 版权声明: This article is licensed under a Creative Commons Attribution 4.0 International License. Code sippets may be used under the MIT Licence.
