'<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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric Postpischil |
