Paul
Paul

Reputation: 25

<C language> switch-case : incorrect boolean results

here is the code lines. programming language : C


#include <stdio.h>
#include <stdbool.h>
bool output(int month,int day)
{
switch(month){
case 1 :
if(day<=31) return true;
break;
case 2 :
if(day<=29) return true;
break;
case 3 :
if(day<=31) return true;
break;
case 4 :
if(day<=30) return true;
break;
case 5 :
if(day<=31) return true;
break;
case 6 :
if(day<=30) return true;
break;
case 7 :
if(day<=31) return true;
break;
case 8 :
if(day<=31) return true;
break;
case 9 :
if(day<=30) return true;
break;
case 10 :
if(day<=31) return true;
break;
case 11 :
if(day<=30) return true;
break;
case 12 :
if(day<=31) return true;
break;
default : 
return false;
}
}

int main()
{
int month, day;
scanf("%d %d",&month,&day);
if(output(month,day))
{
printf("OK! \n");
}
else
{
printf("BAD! \n");
}
printf("%d %d \n",month,day);
return 0;
}

the code result is that, when input data is 2(month) 30(day) in main function, i always get “OK! 2 30” as result. if data of month and day are 2 and 30, the result should be BAD!, because it returns false value of output function case 2.

please help me which part in my code is incorrect.thank you.

Upvotes: 0

Views: 70

Answers (2)

Chris
Chris

Reputation: 36620

You may also wish to consider taking advantage of the fall through behavior of the switch statement, and returning the result of the boolean expressions directly.

bool output(int month,int day) {
    switch (month) {
        case 2:
        return day <= 29;

        case 4:
        case 6:
        case 9:
        case 11:
        return day <= 30; 

        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12 :
        return day <= 31;

        default : 
        return false;
    }
}

Upvotes: 2

Eric Postpischil
Eric Postpischil

Reputation: 223758

There is no return after the switch statement, so, whenever any of the cases executes a break, the function ends without returning a value. When the main routine attempts to use the value of the function, the behavior is undefined.

Add return false; at the end of the function.

Alternately, you could change all the cases to return values and never break, as with:

case 1: return day <= 31;
case 2: return day <= 28;
case 3: return day <= 31;
…

Turn on warnings in your compiler and pay attention to them. Start with -Wmost with Clang, -Wall with GCC, and /W3 with MSVC.

Upvotes: 2

Related Questions