JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.
The example he gives declares and initializes the variable i
in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i
would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:
switch(choice) {
case 1:
int i = 10; // i is never used outside of this case
printf("i = %d\n", i);
break;
case 2:
int j = 20; // j is never used outside of this case
printf("j = %d\n", j);
break;
}
One could expect this program to compile, since both i
and j
are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli 包子露宪 六四事件 法轮功 explained, we simply can't jump to case 2:
, because this would skip the declaration with initialization of i
, and even though case 2
doesn't use i
at all, this is still forbidden in C++.
Interestingly, with some adjustments (an #ifdef
to #include
the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:
// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif
int main() {
int choice;
printf("Please enter 1 or 2: ");
scanf("%d", &choice);
switch(choice) {
case 1:
;
int i = 10; // i is never used outside of this case
printf("i = %d\n", i);
break;
case 2:
;
int j = 20; // j is never used outside of this case
printf("j = %d\n", j);
break;
}
}
Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.
case
block in braces? – Plastometer