I am trying to create different data structures based on what the user inputs, I am wanting to use a switch to determine it. But the compiler is giving errors, I am not sure If i just cant create structures like this or if I am missing something obvious in my switch. The compiler error is saying "initialisation of 's' is skipped by 'default' label. I think that means in the case of the default case, s will not be initialised, which I am fine with, so can I not do it this way, or have i created something wrong in my switch statement.
It's because technically your stack s (in the case 1) is in the same scope as your default case, so you could access s without having initialized it.
To prevent this error, you can wrap the case in an extra pair of braces.
With only two case blocks it might be better to go if/else instead. A switch works better when there are multiple possible blocks of code to choose which one(s) to execute.
Another way to shut the compiler up other than making a case block explicit with braces is move the stack variable's initialization to outside the switch.
1 2 3 4 5 6 7 8 9 10 11 12 13
stack s(5); // initialize here so the variable is within all the case blocks
switch (i)
{
case 1:
{
// ...
break;
}
default:
// ...
}
something like
switch
{
case 1:
stack s; blah blah..
case 2:
vector<something> s;
blah blah.
case 3:... etc
}
then you may be asking about a variant or a union (union is a cruder older way). You can also dive off into void pointers (make a little class and stuff a type in it so it knows what it really is?) or handcook something (you can stuff anything into a byte array, if you so desire, including its type and/or size up front pascal string style). But the variant is the way to do this idea, the others work but are a bit barbaric. You can also do it with templates but that may be overkill(?).
Thank you all for the replies. The switch will contain more cases when I get further into it, it will not just be the one case.
Another way to shut the compiler up other than making a case block explicit with braces is move the stack variable's initialization to outside the switch.
I had tried that, but the complier was giving me an error ( I have tried it again since your suggestion and it is working now - think there is a problem with my vs and it randomly throws errors for no reason)
Anyway I just used Gandos method and put some extra braces around it, and that solved my issue, so thank you Gando
in line 14 you define a stack, but do not give it its template type. Also there is not ctor that I know of that allows defining an initial size of the stack. Unlike what you can do with a vector.
I was also unable to find any "print" function for a stack. Actually I have never heard of a "print" function for a stack. Unless there is change in the 2020 standard or the next standard.
The above code produces this output:
Enter value for data structure 1
2
4
6
7
10
10
7
6
4
2
Press Enter to continue: