I have a short question, why can't we use iterator initializations in switch-case statements? Or am i doing something wrong with this code? I have Dev-C++ and it says "jump to case label crosses initialization of std::_List_iterator<int> i"
#include <iostream>
#include <list>
using namespace std;
main()
{
int a = 1;
switch(a) {
case 1:
list<int>::iterator i;
break;
default:
;}
#include <string>
#include <iostream>
int main() {
int a = 2;
switch (a) {
case 1:
std::string str;
case 2:
cout << str << '\n';
break;
default:
break;
}
}
if a = 1, then everything is ok, str is initialized, and then printed out (remember the flow jumps over labels, if it doesn't see a break;) , BUT if a = 2 then we skip initializing str, and just print it out, which is why your compiler gives you this error. You can make a local scope with {} there to avoid this :
It is illegal to define a local variable within a switch case because initialization does not go past a case. Though there is a workaround if you absolutely must use this. Create your own scope within the case which your variable will be local to.
Ex.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int main()
{
int a = 1;
switch(a) {
case 1:
{ // create a new scope for the variable to live
int x = 1;
// do whatever else you want for case 1
}
break;
default:
break;
}
}
Also, a better question is "why not use int main()?". C++ compilers don't automatically add int to main(). VC++ doesn't.
For basic types, when you are just declaring them you are not initializing them. To call their 'constructor' you can use the explicit syntax int b(4); or the assignment-like syntax int b = 4; but the latter is different from
1 2
int b;
b = 4; // assignment operator, not constructor
For objects ( as an iterator ) the constructor will always be called. If you don't provide any value with = nor with ( ) the default constructor ( if it exists ) will be calles
Okay. Thanks. I understand that we can't use constructors in switch-case statements. But i like playing interesting things like this and usually i'm being stopped something like "ISO C++ forbids 'something something' ". But this is different (it gives different error). Because compiler let declare natural types but isn't let initialize constructors and give error to them. This whole thing didn't make sense and leads to something like this...
#include <iostream>
usingnamespace std;
int main()
{
int a = 2;
switch (a) {
case 1:
int b;
cout << "b is declared" << endl;
cout << "b = " << b << endl; //garbage value...
break;
default:
cout << "b is not declared" << endl;
b = 3; //assignment to b which is not declared...
cout << "b = " << b << endl; }
cin.get();
}
On the other hand if statements are different...
1 2 3 4 5 6 7 8 9
#include <iostream>
usingnamespace std;
int main()
{
if(1 == 1) int b;
b = 4;
}