长度为0的可变长度数组? [英] Variable Length Array with length 0?

查看:371
本文介绍了长度为0的可变长度数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,通常不允许数组的大小为0(除非我使用一个或其他编译器端扩展名).

In C, an array normally isn't allowed to have size 0 (unless I use the one or other compiler-side extension).

OTOH,有些VLA的长度可能变为0.

OTOH, there are VLAs whose length might turn out to be 0.

他们允许吗?

我正在谈论以下代码:

void send_stuff()
{
    char data[4 * !!flag1 + 2 * !!flag2];
    uint8_t cursor = 0;
    if (flag1) {
        // fill 4 bytes of data into &data[cursor]
        cursor += 4;
    }
    if (flag2) {
        // fill 2 bytes of data into &data[cursor]
        cursor += 2;
    }
}

结果是一个长度为0、2、4或6的data数组,具体取决于标志的组合.

The result is a data array with a length of 0, 2, 4 or 6, depending on the combination of the flags.

现在的问题是:对于数组长度为0的情况,此代码是否有效?

The question is now: Is this valid code for the case the array turns out to have length 0?

推荐答案

如果我们转到

This is not valid, if we go to the draft C99 standard section 6.7.5.2 Array declarators paragraph 5 says (emphasis mine):

如果大小是一个不是整数常量的表达式 表达式:如果它出现在函数原型作用域的声明中, 它被视为由*代替;否则,每次 评估后的其值应大于零.[...]

if the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero.[...]

事实上,在clang中,启用了消毒剂使用-fsanitize=undefined标志的未定义行为会在这种情况下生成运行时警告实时查看:

In fact with clang enabling the sanitizer for undefined behavior using the -fsanitize=undefined flag can generate a run-time warning for this case see it live:

运行时错误:可变长度数组绑定的结果为非正值0

runtime error: variable length array bound evaluates to non-positive value 0

这篇关于长度为0的可变长度数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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