簡體   English   中英

sizeof 是在編譯時還是運行時求值?

[英]Does sizeof evaluate at compile-time or runtime?

我對sizeof運算符的評估時間感到困惑。
什么時候評估 sizeof 運算符?

它的評估時間(編譯時或運行時)是否取決於語言(C?C++?)?

對於在 C++ 中運行時創建的對象,我們可以使用sizeof嗎?

在幾乎所有情況下, sizeof都是基於靜態類型信息進行評估的(基本上是在編譯時)。

一個例外(我認為是唯一的)是 C99 的可變長度數組 (VLA)。

幾乎總是編譯時間。 但您可能會對以下示例感興趣:

char c[100];
sizeof(c); // 100

char* d = malloc(100);
sizeof(d); //probably 4 or 8.  tells you the size of the pointer!

BaseClass* b = new DerivedClass();
sizeof(b); //probably 4 or 8 as above.

void foo(char[100] x) {
    sizeof(x); //probably 4 or 8.  I hate this.  Don't use this style for this reason.
}

struct Foo {
    char a[100];
    char b[200];
};

sizeof(struct Foo); //probably 300.  Technically architecture dependent but it will be
//the # of bytes the compiler needs to make a Foo.

struct Foo foo;
sizeof(foo); //same as sizeof(struct Foo)

struct Foo* fooP;
sizeof(fooP); //probably 4 or 8

class ForwardDeclaredClass;

ForwardDeclaredClass* p;
sizeof(p); //4 or 8
ForwardDeclaredClass fdc; //compile time error.  Compiler
//doesn't know how many bytes to allocate

sizeof(ForwardDeclaredClass); //compile time error, same reason

在 C 中,它並不總是編譯時操作,如以下代碼所示:

#include <stdio.h>
#include <stdint.h>

int main(void) {
    int x;
    scanf("%d", &x);   // Value X is not known until run-time
    
    uint16_t data[x];  // VLA: has flexible size depending on input
    
    printf("Value x is: %d\nSize is: %zu\n", x, sizeof(data));
    // sizeof produces proper results at runtime
    
    return 0;
}

直到運行時才知道數組data的大小,並且 sizeof 運算符仍然可以正常工作。

這是 C++ 選擇不支持 VLA 的幾個原因之一。

編譯時,因為它是在編譯時計算大小。“編譯時”是您構建代碼的時間——編譯器將您的源代碼轉換為 IL 的時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM