为什么要"sizeof(a?true:false)"?给出四个字节的输出? [英] Why does "sizeof(a ? true : false)" give an output of four bytes?
本文介绍了为什么要"sizeof(a?true:false)"?给出四个字节的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
关于三元运算符,我有一小段关于sizeof
运算符的代码:
I have a small piece of code about the sizeof
operator with the ternary operator:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool a = true;
printf("%zu\n", sizeof(bool)); // Ok
printf("%zu\n", sizeof(a)); // Ok
printf("%zu\n", sizeof(a ? true : false)); // Why 4?
return 0;
}
输出( GCC ):
Output (GCC):
1
1
4 // Why 4?
但是在这里
printf("%zu\n", sizeof(a ? true : false)); // Why 4?
三元运算符返回boolean
类型,而sizeof bool
类型为C中的1
字节.
the ternary operator returns boolean
type and sizeof bool
type is 1
byte in C.
然后为什么sizeof(a ? true : false)
给出四个字节的输出?
Then why does sizeof(a ? true : false)
give an output of four bytes?
推荐答案
这是因为您拥有#include <stdbool.h>
.该标头将宏 true
和false
定义为1
, 0
,所以您的声明如下所示:
It's because you have #include <stdbool.h>
. That header defines macros true
and false
to be 1
and 0
, so your statement looks like this:
printf("%zu\n", sizeof(a ? 1 : 0)); // Why 4?
sizeof(int)
在您的平台上为4.
这篇关于为什么要"sizeof(a?true:false)"?给出四个字节的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文