Home > Backend Development > C++ > body text

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

PHPz
Release: 2023-09-21 10:09:03
forward
1726 people have browsed it

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;
}
Copy after login

Output

This will give the output:

13
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template