+ 4
Whats wrong with this code can anybody tell?
#include <stdio.h> int main() { int age=40; switch { age '15'=printf("to young"),//case1 '40'=printf("adult"),//case2 '70'=printf("old")//case3 } return 0; }
5 Answers
+ 6
0. You aren't checking the age in the switch statement.
1. You have no cases.
2. The numbers shouldn't be enclosed in single quotes.
3. You need a colon after each case.
4. You need a break statement after each case (or you'll fall through to the next statement)
5. (Optional) You can add a default condition to handle values you are not checking for.
Change it to:
#include <stdio.h>
int main(void)
{
int age = 40;
switch (age) {
case 15:
printf("too young\n");
break;
case 40:
printf("adult\n");
break;
case 70:
printf("old\n");
break;
default:
printf("Unexpected age.\n");
break;
}
return 0;
}
And it'll work as expected.
+ 4
switch(age)
{
case 15:printf("too young");
break;
case 40:printf("adult");
break;
case 70:printf("old");
break;
}
+ 3
Cluck'n'Coder thanks bro for explaining.
+ 2
#include<stdio.h>
int main(void)
{
int age=40;
Switch (age>0)/* if we declare age>0 it will good in practical way*/
{
case 15:printf("too young\n");
break;
case 40:printf("adult\n");
break;
case 70:printf("old\n");
break;
}
return 0;
}