繁体   English   中英

可以请解释一下这个程序的 output 是如何浮动的

[英]can some please explain how float is the output of this program

有人可以解释一下这个程序的output是如何浮动的吗?我无法理解

#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");
}

实际上,三元运算符并没有完全按照您的想法返回,但也不是 @user15790236 的想法。 三元运算符一个运算符,因此它期望在冒号两侧具有相同类型的 arguments。 由于您有不同的类型,因此 integer 被提升为浮点数,因此表达式的类型为浮点数。

三元运算符并没有返回您认为的那样。

( (x == 2)? f: i )实际上返回 i 的,它是按值,然后作为 int 处理,而不是短 int - 因此,根据您的 64 位编译器,大小为 4 个字节。 换句话说,三元运算符的返回是 i 中的内容的副本,而不是 i 本身。

通过检查以下值向自己证明这一点:

sizeof(2)

为了得到你所期望的,你可以说:

( (x==2) ? sizeof(f) : sizeof(i) )

您可能要考虑的下一个问题是,为什么编译器选择 int 作为类型,而 short 可以解决问题。 看看隐式类型提升规则

从 C11 开始,要注意type ,而不是尝试sizeof(type)比较,请使用_Generic

#include <stdio.h>

#define type(X) _Generic((X), \
    short: "short", \
    int: "int", \
    float: "float", \
    double: "double", \
    default: "default" \
)

int main(void) {
  int x = 1;
  short int i = 2;
  float f = 3;
  puts(type(x));
  puts(type(i));
  puts(type(f));
  puts(type((x == 2) ? f : i));
}

Output

int
short
float
float

(x == 2)? f: i (x == 2)? f: i是一个float ,正如@SGeorgiades指出的那样, a?b:c的类型是相同的,无论a是否为真。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM