Jump Bypasses Variable Initialization in Switch Statement
I Need an Std: : Vector or an Std: : String in My Switch Case for Some Purpose. So, I Wrote the Following Dummy Code to See If It Works: #Include #Include Int...
I need an std:: vector<char> or an std:: string in my switch case for some purpose. So, I wrote the following dummy code to see if it works:
#include <iostream>
#include <string>
int main() {
int choice = 0;
do {
std:: cout << "Enter Choice" << std::endl;
std:: cin >> choice;
switch(choice) {
case 1:
std::cout << "Hi";
break;
case 2:
std::string str;
std::cin >> str;
break;
case 3: //Compilation error, Cannot jump from switch statement to this case label
std::cout << "World" << std:: endl;
break;
default:
std:: cout << "Whatever" << std:: endl;
}
} while(choice != 5);
return 0;
}
Ok, I somewhat got it that str is an object of std:: string type. So, I am trying to jump through this variable initialization.
Then why a definition of C style string does not cause compilation error:
#include <iostream>
#include <string>
int main() {
int choice = 0;
do {
std:: cout << "Enter Choice" << std::endl;
std:: cin >> choice;
switch(choice) {
case 1:
std::cout << "Hi";
break;
case 2:
char str[6];
std::cin >> str;
break;
case 3:
std::cout << "World" << std:: endl;
break;
default:
std:: cout << "Whatever" << std:: endl;
}
} while(choice != 5);
return 0;
}
How can I make the first code to work?
2 Answers
char str[6]; is default-initialized. In case of C arrays of simple values with automatic storage duration ("allocated on stack") it means "no initialization at all", so I guess it's not an error.
If you, however, initialize the array like char str[6] = {}, it will yield an error.
I suggest you put extra curly braces so str is in its own scope and is not visible in further case statements:
#include <iostream>
#include <string>
int main() {
int choice = 0;
do {
std:: cout << "Enter Choice" << std::endl;
std:: cin >> choice;
switch(choice) {
case 1:
std::cout << "Hi";
break;
case 2: { // Changed here
std::string str;
std::cin >> str;
break;
}
case 3: // `str` is not available here, no compilation error
std::cout << "World" << std:: endl;
break;
default:
std:: cout << "Whatever" << std:: endl;
}
} while(choice != 5);
return 0;
}
Where to put brackets is a styling preference.
Just create a new block for the variable with an extra pair of braces
case 2:
{ // <-- start new block for str
std::string str;
std::cin >> str;
break;
} // <-- end of block, str will be destroyed here