0

Why can't c++ define variables after the case? I think this is safe. Suppose int a = 2; this is unsafe, but int a is also unsafe and may go wrong, why the former will report an error, but the latter will not.

#include <iostream>
using namespace std;
int main()
{
    int i;
    i = 2;
    switch (i)
    {
    case 1:
        int j = 10;//Due to initialization, this is not allowed.
        j++;
    case 2:
        j = 20;
        cout << j << endl;
    case 3:
    case 4:
    case 5:
    default:
        break;
    }
}

#include <iostream>
using namespace std;
int main()
{
    int i;
    i = 2;
    switch (i)
    {
    case 1:
        int j;//Because there is no initialization, this is allowed.
        j = 10;
        j++;
    case 2:
        j = 20;
        cout << j << endl;
    case 3:
    case 4:
    case 5:
    default:
        break;
    }
}
QianJing
  • 9
  • 1
  • 3
    Does this answer your question? [Why can't variables be declared in a switch statement?](https://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement) – zerocukor287 Jul 15 '21 at 00:32
  • See https://stackoverflow.com/questions/2392655 It's just the language rules. If the type is POD, and *it doesn't have an initializer* it can cross a case label. – cigien Jul 15 '21 at 00:34
  • you can even define and declare variables before the int main() if you want to go beyond c++ rules. – Sarah Jul 15 '21 at 00:39

0 Answers0