c++ - 可以使用 switch 语句处理的最大案例数

标签 c++ switch-statement standards

这是出于好奇。我在单个 switch 中最多可以拥有多少个 switch case,包括 default: case。我的意思是这样的:

switch(ch)
{
case 1:
//some statement
break;
case 2: 
//some statement
break;
.
.
.
.
case n:
//some statement
break;
default:
//default statement
}

我的问题是我们可以在这里获得的最大值是多少?虽然这在程序上并不重要,但我发现这是一个相当有趣的想法。我搜索了一些博客,发现了一个声明here .

根据我的文档,据说:

Standard C specifies that a switch can have at least 257 case statements. Standard C++ recommends that at least 16,384 case statements be supported! The real value must be implementation dependent.

但是我不知道这个信息有多准确,有人能给我一个想法吗? 依赖于实现是什么意思?假设有这样的限制,我可以以某种方式将其更改为更高或更低的值吗?

最佳答案

draft C++ standard 附件 B(信息性)实现数量 说(强调我的):

Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process. Every implementation shall document those limitations where known. [...]

The limits may constrain quantities that include those described below or others. The bracketed number following each quantity is recommended as the minimum for that quantity. However, these quantities are only guidelines and do not determine compliance.

并包括以下项目:

— Case labels for a switch statement (excluding those for any nested switch statements) [16384].

但这些并不是硬性限制,只是对最低限度的建议。

实现是编译器、标准库和支持工具,因此实现依赖基本上意味着对于这种情况,编译器将决定限制是什么,但它应该记录这个限制。标准草案在 1.3.10 部分将实现定义的行为定义为:

behavior, for a well-formed program construct and correct data, that depends on the implementation and that each implementation documents

我们可以看到 gcc does not impose a limit对于C:

GCC is only limited by available memory.

在这种情况下也应该涵盖 C++,它看起来像 Visual Studio也不设限:

Microsoft C does not limit the number of case values in a switch statement. The number is limited only by the available memory. ANSI C requires at least 257 case labels be allowed in a switch statement.

我找不到 clang 的类似文档。

关于c++ - 可以使用 switch 语句处理的最大案例数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20355948/

相关文章:

javascript switch() 或 if()

c++ - 重新定义 C++ 关键字是否合法?

javascript - 条件 Action 逻辑应该去哪里?

c++ - 另一种创建随机数的方法

javascript - jquery $(this).attr(…) 返回未定义

Powershell "special"开关参数

c - 仅包含标识符的表达式会读取 volatile 变量吗?

c++ - 在 C++ 中,将动态分配的动态对象传递给函数(总是)是个坏主意吗?

c++ - 将文件读入两个数组

c++ - Vim 中文件的一部分的快照 : hide comments and blank lines