why this switch statment is not valid??? reason
switch (n % 10)
case 2:
{
case 4:
case 6:
case 8:
cout << "Even";
break; case 1:
case 3:
case 5:
case 7:
cout << "Odd"; break; }
The first reason in the function int main n was not declared.
The second reason the syntax for the switch case is wrong. The correct syntax for switch case is
switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);
}
A switch statement is subject to the following rules.
In a switch statement, the expression must be of an integral or enumerated type, or of a class type with a single conversion function to an integral or enumerated type.
A switch can contain any number of case statements. Each case is followed by a colon and the value to be compared to.
A case's constant expression must be of the same data type as the switch's variable, and it must be either a constant or a literal.
When the variable being turned on equals a case, the statements that follow it will run until a break statement is reached.
The switch terminates when a break statement is reached, and the flow of control jumps to the line after the switch statement.
A break isn't required in every circumstance. If no break exists, the control flow will continue through the following cases until a break is found.
A default case can be specified in a switch statement and must occur at the end of the switch. When none of the other situations are true, the default case can be utilized to complete a task. In the default instance, no break is required.
Comments
Leave a comment