Home  >  Article  >  Backend Development  >  Why can't variables be declared in the C/C++ switch statement?

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

PHPz
PHPzforward
2023-09-21 10:09:031649browse

Why cant variables be declared in the C/C++ switch statement?

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

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;
}

Output

This will give the output:

13

If you try to declare a variable in a public place, you may get an error , because jumping to a case label is the same as using goto, you are not allowed to skip the declaration of a local variable in the same scope because you may use it elsewhere in the scope.

The above is the detailed content of Why can't variables be declared in the C/C++ switch statement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete