sizeof 操作数中的 VLA 和副作用

VLAs and side-effect in sizeof's operand

我知道 sizeof 从不评估其操作数,除非在特定情况下所述操作数是 VLA。或者,我以为我知道。

void g(int n) {
    printf("g(%d)\n", n);
}

int main(void) {
    int i = 12;

    char arr[i]; // VLA

    (void)sizeof *(g(1), &arr); // Prints "g(1)"
    (void)sizeof (g(2), arr);   // Prints nothing

    return 0;
}

这是怎么回事?

以防万一,这是在 Coliru 上使用 GCC 5.1 编译的。

看来我应该三思而后发,因为刚发完就给我留下了深刻的印象

我对 sizeof 如何与 VLA 交互的理解实际上是正确的,正如以下引用所证实的(感谢@this!):

6.5.3.4 The sizeof and _Alignof operators
If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant

这不是导致这种(对我来说)令人惊讶的行为的原因。

(void)sizeof (g(2), arr);

(g(2), arr) 子表达式中,逗号运算符触发 arr 的数组到指针衰减。因此,sizeof 的操作数不再是一个 VLA,而是一个普通的 char*,它退回到不计算它的操作数。

Apparently此行为已在 C++ 中更改,其中逗号运算符将不再衰减数组。