I am new to C and need help. My code is the following.
#include<stdio.h>
#include<conio.h>
void main()
{
int suite=2;
switch(suite)
{
case 1||2:
printf("hi");
case 3:
printf("byee");
default:
printf("hello");
}
printf("I thought somebody");
getche();
}
I am working in Turbo C and the output is helloI thought somebody
. There's no error message.
Please, let me know how this is working.
do this:
This will be a lot cleaner way to do that. The expression
1||2
evaluates to1
, sincesuite
was 2, it will neither match 1 nor 3, and jump todefault
case.You
switch
on value2
, which matchesdefault
case inswitch
statement, so it prints "hello" and then the last line prints "I thought somebody".Becomes
true
. so it becomescase 1:
but the passed value is 2. so default case executed. After that yourprintf("I thought somebody");
executed.Just put brackets and see the magic.
In your code,the program just check the first value and goes down.Since,it doesn't find 2 afterwards it goes to default case.
But when you specific that both terms i.e. 1 and 2 are together, using brackets, it runs as wished.
Results in
because
1 || 2
evaluates to1
(and remember; only constant integral expressions are allowed incase
statements, so you cannot check for multiple values in onecase
).You want to use: