簡體   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