简体   繁体   English

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

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

can some please explain how float is the output of this program I am unable to understand有人可以解释一下这个程序的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");
}

Indeed the ternary operator is not returning quite what you think it is, but it is also not quite what @user15790236 thinks either.实际上,三元运算符并没有完全按照您的想法返回,但也不是 @user15790236 的想法。 The ternary operator is an operator, and as such it expects arguments of the same type on either side of the colon.三元运算符一个运算符,因此它期望在冒号两侧具有相同类型的 arguments。 Since you have different types, the integer is promoted to float, and thus the expression is of type float.由于您有不同的类型,因此 integer 被提升为浮点数,因此表达式的类型为浮点数。

The ternary operator is not returning quite what you think it is.三元运算符并没有返回您认为的那样。

( (x == 2)? f: i ) actually returns the value of i, which is by value and is then handled as an int, not a short int - thus, 4 bytes in size according to your 64bit compiler. ( (x == 2)? f: i )实际上返回 i 的,它是按值,然后作为 int 处理,而不是短 int - 因此,根据您的 64 位编译器,大小为 4 个字节。 Put another way, the return from the ternary operator is a copy of what is in i, not i itself.换句话说,三元运算符的返回是 i 中的内容的副本,而不是 i 本身。

Prove this to yourself by checking the value of:通过检查以下值向自己证明这一点:

sizeof(2)

To get what you seem to expect, you could instead say:为了得到你所期望的,你可以说:

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

The next question you may want to consider is why does the compiler pick int for the type when a short would do the trick.您可能要考虑的下一个问题是,为什么编译器选择 int 作为类型,而 short 可以解决问题。 Have a peek at Implicit type promotion rules看看隐式类型提升规则

Since C11, to note the type , rather attempt sizeof(type) compares, use _Generic .从 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 Output

int
short
float
float

(x == 2)? f: i (x == 2)? f: i is a float as @SGeorgiades well points out, the type of the a?b:c is the same, regardless if a is true or not. (x == 2)? f: i是一个float ,正如@SGeorgiades指出的那样, a?b:c的类型是相同的,无论a是否为真。

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

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