VLA和sizeof操作数的副作用 [英] VLAs and side-effect in sizeof's operand

查看:160
本文介绍了VLA和sizeof操作数的副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道sizeof从不评估其操作数,除非在特定情况下该操作数是VLA.或者,我思想我知道.

I know that sizeof never evaluates its operand, except in the specific case where said operand is a VLA. Or, I thought I knew.

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编译的.

Just in case, this is compiled with GCC 5.1 on Coliru.

推荐答案

在发布之前,我似乎应该三思而后行,因为它在我刚发布后就给我留下了深刻的印象.

It seems that I should think twice before posting, because it struck me right after I did.

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

My understanding of how sizeof interacts with VLAs is actually correct, as the following quote confirms (thanks @this !) :

6.5.3.4 sizeof_Alignof运算符
如果操作数的类型是可变长度数组类型,则对操作数求值;否则,将求值.否则,不对操作数求值,结果为整数常量

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

这不是导致这种(对我而言)令人惊讶的行为的原因.

That's not what is causing this surprising (to me) behaviour.

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

(g(2), arr)子表达式中,逗号运算符触发arr的数组到指针的衰减.因此,sizeof的操作数不再是VLA,而是普通的char*,并且回退到不评估其操作数.

In the (g(2), arr) subexpression, the comma operator triggers arr's array-to-pointer decay. Thus, sizeof's operand is no longer a VLA, but a plain char*, and it falls back to not evaluating its operand.

显然此行为已在C ++中更改,其中逗号运算符不再衰减数组.

Apparently this behaviour has been altered in C++, where the comma operator won't decay arrays anymore.

这篇关于VLA和sizeof操作数的副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆