luciferjack
luciferjack

Reputation: 109

Why my code doesn't work if i don't put case 0 in switch

I was finding the greatest number using switch case in c. Here if I start the switch with case 0 the program executes perfectly.

 #include <stdio.h>
 #include <stdlib.h>

  int main()
     {
     int a,b;
     scanf("%d%d",&a,&b);


     switch(a>b)
     {
     case 0:
        printf("%d is maximum",b);
        break;
     case 1:
        printf("%d is maximum",a);
        break;
     }


    return 0;

But when I use case 1 instead of case 2.The program takes the input but doesn't show any result. What's the reason?

#include <stdio.h>
#include <stdlib.h>

int main()
{
     int a,b;
     scanf("%d%d",&a,&b);


     switch(a>b)
     {
     case 1:
        printf("%d is maximum",b);
        break;
     case 2:
        printf("%d is maximum",a);
        break;
     }


    return 0;

Upvotes: 2

Views: 668

Answers (2)

Adrian Mole
Adrian Mole

Reputation: 51825

The comparison a>b is an expression that will evaluate to either true or false. When representing (or testing) these "Boolean" values in C, false is equivalent to zero and true is equivalent to one.

So, the switch statement in your first code block will do as you expect. However, in your second block, the tested expression can never have the value 2 so, if a is not greater than b, nothing will be printed! (However, if a is larger than b, then the case 1: block will run.)

PS: If the evaluation of the expression in the brackets following the switch does not match any of the given cases inside the switch (...) {} block, then your code will silently ignore that block … unless you add a default: block (traditionally added at the end, but it can go anywhere a case X: could). Maybe you could try this to see for yourself.

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

For starters in one switch statement there may not two identical case labels. SO this code should not compile

 switch(a>b)
 {
 case 1:
    printf("%d is maximum",b);
    break;
 case 1:
    printf("%d is maximum",a);
    break;
 }

From the C Standard (6.8.4.2 The switch statement)

3 The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion. ...

In C the value of a logical expression (as for example, a > b ) can be either integer 0 (false) or integer 1 (true). So the case labels in this switch statement are correct

 switch(a>b)
 {
 case 0:
    printf("%d is maximum",b);
    break;
 case 1:
    printf("%d is maximum",a);
    break;
 }

Upvotes: 1

Related Questions