Maximum number of cases that can be addressed using switch statement

c++, standards, switch-statement

Solution

The draft C++ standard `Annex B (informative) Implementation quantities` says (emphasis mine):

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.

and includes the follow item:

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

but these are not hard limits only a recommendation on minimums.

The implementation is the compiler, standard library and supporting tools and so implementation dependent basically means for this case the compiler will decide what the limit is but it should document this limit. The draft standard defines implementation-defined behavior in section `1.3.10` as:

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

We can see that `gcc` does not impose a limit for C:

GCC is only limited by available memory.

which should also cover C++ in this case and it looks like Visual Studio also does not place a limit:

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.

I can not find similar documentation for `clang`.

Problem

This is out of curiosity. What is the maximum number of switch cases I can have in a single switch including the default: case. I mean like this: ``` switch(ch) { case 1: //some statement break; case 2: //some statement break; . . . . case n: //some statement break; default: //default statement } ``` My question is what is the maximum value that we can have here? Although this is not programatically significant, I found this a rather intriguing thought. I searched some blogs and found a statement here. From a doc I have, it is said that: 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. But I don't know how accurate this information is, can somebody give me an idea? Also what does it mean by implementation dependent? Suppose there is a limit like this, can I somehow change it to a higher or lower value?

Original source

Related problems