[英]Why in conditional operator (?:), second and third operands must have the same type?
[英]Why it is the type/size of the conditional operator?
#include <stdio.h>
int main()
{
int x = 1;
short int i = 2;
float f = 3;
if (sizeof((x == 2) ? f : i) == sizeof(float))
printf("float\n");
else if (sizeof((x == 2) ? f : i) == sizeof(short int))
printf("short int\n");
return 0;
}
谁能帮我解决这个问题,为什么它打印浮点数,为什么它为 sizeof(x==2) 提供 4,谁能帮我看流程图? ''' sizeof((x == 2)? f: i) == sizeof(float) ''' 这段代码如何在 if 部分给出 true 或 1?
编写代码是为了演示如何确定条件运算符的结果类型。
如果结果类型取决于第一个操作数选择了第二个和第三个操作数中的哪一个,那么(x == 2)? f: i
(x == 2)? f: i
将是float
或short int
,具体取决于x == 2
。 因为在这个例子中, x == 2
是假的,所以它会是short int
。 然而,代码的执行表明情况并非如此,假设float
有四个字节而short int
有两个字节,这在当前的 C 实现中很常见。
在(x == 2)? f: i
(x == 2)? f: i
, x == 2
为假(因为x
的值为 1),所以结果值为i
的值。 但是,测试sizeof((x == 2)? f: i) == sizeof(float)
得出 true,表明即使选择i
作为结果值,结果类型的大小为float
,而不是short int
的大小。
确定条件运算符结果类型的规则在 C 2018 6.5.15 5. 对于算术操作数,它说“如果将它们应用于这两个操作数,通常的算术转换将确定的结果类型是结果的类型。” C 2018 6.3.1.8中规定了通常的算术转换。 对于float
和short int
,它们产生float
。 因此,其第二个和第三个操作数具有float
和short int
的条件运算符的结果类型为float
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.