为什么我不能“默认"?或"goto case x;";交换机选择结构中? [英] Why can't I "goto default;" or "goto case x;" within a switch selection structure?

查看:47
本文介绍了为什么我不能“默认"?或"goto case x;";交换机选择结构中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C11的6.8.1节 C89 似乎都表明 default case x (其中 x 是一些恒定表达)是带有标签的语句的示例,以及与 goto 一起使用的 identifier:样式的标签.

Section 6.8.1 of C11 or C99, or section 3.6.1 of C89 all seem to indicate that default and case x (where x is some constant-expression) are examples of labeled statements, along-side identifier:-style labels that are suitable for use with goto.

我知道我可以在 default: case x:标签之后直接放置一个 identifier:样式的标签.这不是这个问题的意思.我对禁止这种行为背后是否有任何实际理由感到好奇.

I'm aware that I could simply place an identifier:-style label directly following the default: or case x: labels. That's not what this question is about. I'm more curious as to whether there is any actual rationale behind prohibiting this kind of behaviour.

如果可以在 switch 选择结构之外声明 default:标签,那么我会理解,因为 switch 选择结构内部的goto 旨在实现目标.但是, C11的6.4.1节C99 C89的3.1.1禁止将 default 用作除关键字之外的任何其他内容,并且6.8.1将其使用范围进一步限制为仅 switch 结构(或 generic 结构,此处与此无关).

If it were possible to declare default: labels outside of a switch selection structure, then I would understand, as there would be some conflict between where the goto inside of the switch selection structure is intended to aim. However, section 6.4.1 of C11 or C99 or 3.1.1 of C89 prohibits the use of default as anything other than a keyword, and 6.8.1 restricts its use further to switch structures only (or generic structures in C11, which are irrelevant here).

我也将理解是否有多个(可能嵌套的) switch 结构,每个结构都带有 default:(或 case x:)标签,导致含糊不清,但是这些标签的范围似乎仅限于其最内层的 switch 结构内,并且引用超出其范围的任何标识符显然是错误,需要在编译时进行诊断.

I would also understand if multiple (possibly nested) switch structures, each with default: (or case x:) labels introduced ambiguity, however the scope of those labels seems to be restricted to within their inner-most surrounding switch structures, and referring to any identifier outside of its scope is clearly an error requiring a diagnostic at compile-time.

是否在任何标准文档中对此进行了讨论(例如基本原理)?除了是因为是这样"或因为规范说是这样"以外,是否对此行为有任何解释?如果是这样,那是什么解释?

Has this been discussed in any standard documents (e.g. the rationale)? Is there any kind of explanation for this behaviour other than "it is because it is" or "because the spec says so"? If so, what is that explanation?

推荐答案

计数器示例

fun() {
  switch (b) {
     case x:
       doSomething();
       break;
  }
  switch(b2) {
     case x:
       doMore();
       break;
  }

  goto x; // which one?
}

这篇关于为什么我不能“默认"?或"goto case x;";交换机选择结构中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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