0

This is the code that i came up with while solving a book problem where i was asked to write a program that gets input in 12 hour format and gives output in 24 hour format.

Valid inputs are e.g 1:11PM, 1:11P, 1:11pm, 1:11p, 1:11 pm, 1:11 p, 1:11 PM, 1:11 P

Here is the code :

#include<stdio.h>

int main (void)
{
int hr=0,min=0; char time;


scanf("%d : %d %c", &hr, &min, &time);

if(time =='p' || time == 'P' || time == 'PM' || time == 'pm' && hr >= 12)
{
    hr +=12;
}

printf("The 24 hour format time is = %d : %d", hr, min);


printf("% Test result = c", test);

return 0;
}

In the if condition i wrote :

if(time =='p' || time == 'P' || time == 'PM' || time == 'pm' && hr >= 12)

As far as i know char type is only allowed to store 1 character. So why does this work when i give a input like this 9:11 PM. How did it work for this condition?

time == 'pm' || time == 'PM'

The output was :

The 24 hour format time is =21:11

Edit 1 :

GNU GCC Compiler is used. The code is in a single file not in a project.

Martin G
  • 17,357
  • 9
  • 82
  • 98
Monzir
  • 621
  • 4
  • 9
  • 29
  • What compiler are you using? What system are you compiling on, and for (host & target could be different when cross-compiling)? What options are you giving? Did you enable all warnings and debug info ? – Basile Starynkevitch Sep 24 '12 at 17:54
  • 1
    You forgot to enable compilation warnings. If you had done so, the compiler would have warned you were trying to use "multi-character constants". – pmg Sep 24 '12 at 17:55
  • 1
    possible duplicate of [What do single quotes do in C++ when used on multiple characters?](http://stackoverflow.com/questions/7459939/what-do-single-quotes-do-in-c-when-used-on-multiple-characters) – pb2q Sep 24 '12 at 17:57
  • When one condition evaluate to true, the others are usually not tested – Manuel Selva Sep 24 '12 at 17:59

1 Answers1

4

Even without the warning you get (or at least should get) you have the condition time == 'P' which is evaluated as true, and you're done.

Also note that you should wrap all the or's in (), as otherwise the >= 12 is not even checked. E.g.:

((time =='p' || time == 'P') && hr >= 12)
MByD
  • 135,866
  • 28
  • 264
  • 277