Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Why can't variables be declared in a switch statement in C/C++?

Why can't variables be declared in a switch statement in C/C++?


1 Answer
George John

Variables can be declared in a switch statement. You'll just need to declare them and use them within a new scope in the switch statement. For example,

#include<iostream>
using namespace std;

int main() {
   int i = 10;
   switch(i) {
      case 2:
      //some code
      break;
      case 10:{
         int x = 13;
         cout << x;
      }
   }
   return 0;
}

This will give the output:

13

If you try to declare the variable out in the open you might get an error as Jumping to a case label is the same as using goto, so you aren't allowed to jump over a local variable declaration while you're in the same scope as it and might be using it someplace further in that scope.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.