Reputation: 34658
What is the difference between following two code snippets of switch statement?
Which one is better? When can I use both of them?
case 1:
int i = 10;
switch(i)
{
//case
}
case 2:
switch(int i = 10, i)
{
//case
}
In second case, C++17 permitted to initialize variables inside the switch statement.
Upvotes: 1
Views: 226
Reputation: 218228
switch (int i = 42; i)
is C++17 and would restrict the scope of i
to the switch, it would be mostly equivalent to:
// Code before switch
{ // Additional scope
int i = 42;
switch (i) {
// case...
}
}
// Code after switch
It would also apply to if
if (int i = 42; i == foo()) {
// Can use i
} else {
// Can use i
}
Upvotes: 3
Reputation: 11940
In the first version i
lives past the switch
's scope end. You can use it should you need i
later. You can use the second version if your compiler knows C++17.
Upvotes: 5