本文介绍了将案例标签嵌入到if ... else语句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

G ++接受此代码,并且其行为符合我的预期:

G++ accepts this code and it behaves as I'd expect it to:

#include <cassert>

void example (int value, bool condition) {

  switch (value) {
  case 0:
    if (condition) {
  case 1:
      assert(condition || value == 1);
    } else {
      assert(!condition && value == 0);
    }
    assert(value == 0 || value == 1);
  }

}

int main () {
  example(0, false);
  example(1, false);
  example(0, true);
  example(1, true);
}

也许这是一个愚蠢的基本问题,但是,除了代码味道,将 case 标签放在 if ... else 块内是否是有效的C ++,并且会所有行为良好的编译器正确生成的代码在通过 case 1 输入时会跳过 else 块吗?

Maybe this is a silly basic question but, code smell aside, is it valid C++ to put a case label inside an if...else block, and will all well-behaved compilers correctly generate code that will jump over the else block when entered through case 1?

推荐答案

就C ++而言(N3936草案):

As far as C++ is concerned (draft N3936):

  • 通常,作为开关主题的子陈述是复合的,并且case和默认标签出现在(复合)子陈述中包含的顶级语句中,但这不是必需的.(§6.4.2-6)
  • 可以转移到块中,但不能以初始化绕过声明的方式进行.(第6.7-3节)
  • case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels.
  • Usually, the substatement that is the subject of a switch is compound and case and default labels appear on the top-level statements contained within the (compound) substatement, but this is not required.(§ 6.4.2 - 6)
  • It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. (§ 6.7 - 3)

从技术上讲,您在做什么是可以的,当然这并不意味着您应该这样做.

What you are doing is technically ok, of course that doesn't mean you should.

这篇关于将案例标签嵌入到if ... else语句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:08