
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
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 Articles
- Why variables are declared final in Java
- Can we have a return statement in a JavaScript switch statement?
- Switch case statement in C
- Explain switch statement in C language
- Why can't static method be abstract in Java?
- Why a virus can't be killed using antibiotics?
- Can we have a switch statement in JSP for XPath expression?
- Can you use a switch statement around an enum in Java?
- Can we use Switch statement with Strings in java?
- Switch Statement in Java
- How to use strings in switch statement in C#
- Why doesn't JavaScript have a goto statement?
- Why can't a Java class be both abstract and final?
- PHP switch Statement
- Java switch statement

Advertisements