Reputation: 41
Following code compiles on my gcc 5.4.0, doesn't generate any warnings and works fine:
if (a == 0) {
puts("0");
} else switch (a) {
case 1: puts("1"); break;
case 2: puts("2"); break;
default: puts("default"); break;
}
Is if ... else switch ... correct statement?
Upvotes: 3
Views: 1869
Reputation: 6969
What you have is syntactically correct... but it does not make easy reading.
You will likely be pulled up on it if your code is being reviewed - because you're making use of an "un-braced, multi-line statement as part of a conditional".
Prefer to be explicit and write it like so:
if (a == 0) {
puts("0");
} else {
switch (a) {
case 1: puts("1"); break;
case 2: puts("2"); break;
default: puts("default"); break;
}
}
It is legal in the same way that the following is legal:
if (a == 0)
puts("0");
else
puts("not0");
Such constructs can lead to mistakes when re-visiting the code... I seem to remember that one of the recent "popular" vulnerabilities was implemented (by mistake... hopefully) in part due to this "un-braced" use of if
.
Upvotes: 4
Reputation: 5162
Nothing wrong with your code, that is the same of writing this:
if (a == 0) {
puts("0");
} else {
switch (a) {
case 1: puts("1"); break;
case 2: puts("2"); break;
default: puts("default"); break;
}
}
That is perfectly legit. else switch
is not a real statement.
Your statement is
if(condition){code block} else {code block}
code block
can contain any statement, such as your switch
statement.
Upvotes: 3
Reputation: 30489
Syntax of if
is:
if ( condition ) statement-true else statement-false
condition is an expression convertible to a boolean (true/false)
statement-true is a statement which is executed if condition is true
statement-false is a statement which is executed if condition is false
And switch
block is a statement.
So yes, your code exhibit correct statement.
Upvotes: 2
Reputation: 399703
The switch
is a statement, so this is just putting a statement in the else
.
It's no different from
else
a = 0;
or
else
{
switch(a)
{
case 1:
...
}
}
It's not a very common way of writing it, but it's fine.
Upvotes: 3
Reputation: 93264
There's nothing wrong with your code. The grammar for if
... else
is as follows:
attr(optional) if ( condition ) statement-true else statement-false
switch
is a statement, so it is allowed to go after else
.
Note that else if
is not a special construct either, it's just an if
statement after an else
.
Upvotes: 9