C标准中对可变修改类型的switch语句约束的说明 [英] Explanation of switch statement constraints on variably modified types in C standard

查看:160
本文介绍了C标准中对可变修改类型的switch语句约束的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个C编译器,当我谈到switch语句的实现时,一个约束使我很困惑. 标准的第6.8.4.2p2节状态:

I'm writing a C compiler, and when I come to the implementation of the switch statement one constraint confused me a lot. Section 6.8.4.2p2 of the standard states:

如果switch语句中包含关联的大小写或默认标签 具有可变修改类型的标识符的范围,整个 switch语句应在该标识符的范围内.

If a switch statement has an associated case or default label within the scope of an identifier with a variably modified type, the entire switch statement shall be within the scope of that identifier.

带有脚注:

也就是说,声明要么在switch语句之前,要么在switch语句之前 遵循与交换机关联的最后一种情况或默认标签, 在包含声明的块中.

That is, the declaration either precedes the switch statement, or it follows the last case or default label associated with the switch that is in the block containing the declaration.

我真的不明白这个约束的含义.可以给我一个例子吗?

I can't really understand what this constraint means. Can some one give me an example?

推荐答案

这是说,如果一个案例能够看到可变修饰的数组,则整个switch语句必须还能看到它.

What this is saying is that if one case is able to see a variably modified array, then the entire switch statement MUST be able to see it as well.

这意味着以下代码是合法的:

This means that the following code is legal:

void switch_test(int size)
{
    int array[size];
    ...
    // code to populate array
    ...
    switch (expr) {
    case 1:
        printf("%d\n", array[0]);
        break;
    case 2:
        // do something else
    }
}

但是此代码不是:

void switch_test(int size)
{
    switch (expr) {
    case 2:
        // do something else
        int array[size];   // ILLEGAL, VLA in scope of one label but not all
    case 1:
        ...
        // code to populate array
        ...
        printf("%d\n", array[0]);
    }
}

后者不合法的原因是因为如果代码跳至案例1,则可能无法正确创建array,因为VLA的大小是在运行时确定的.确保在switch语句之前可以看到VLA可以避免此问题.

The reason the latter is illegal is because if the code were to jump to case 1 then array might not have been created properly since the size of a VLA is determined at run time. Ensuring that the VLA is visible before the switch statement avoids this issue.

这篇关于C标准中对可变修改类型的switch语句约束的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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