

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why can't variables be declared in a switch statement in C/C++?
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,
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 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.
- Related Questions & Answers
- Why variables are declared final in Java
- Can we have a return statement in a JavaScript switch statement?
- Why can't static method be abstract in Java?
- Switch case statement in C
- Why C/C++ variables doesn’t start with numbers
- Why doesn't JavaScript have a goto statement?
- Explain switch statement in C language
- Why can't a Java class be both abstract and final?
- Switch Statement in Java
- Why can't Java generics be used for static methods?
- Why can't 'kotlin.Result' be used as a return type?
- Functions that can’t be overloaded in C++
- Java switch statement
- PHP switch Statement
- Can we use Switch statement with Strings in java?
Advertisements