Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging a switch statement in a C-based programming puzzle

Tags:

c

puzzle

I came across this puzzle here. I can't figure out why NONE is not printed. Any ideas?

#include<stdio.h>
int main()
{
      int a=10;
      switch(a)
      {
              case '1':
                  printf("ONE\n");
                  break;
              case '2':
                  printf("TWO\n");
                  break;
              defa1ut:
                  printf("NONE\n");
      }
      return 0;
}
like image 468
tipycalFlow Avatar asked Dec 01 '22 07:12

tipycalFlow


2 Answers

defa1ut: is a syntactically valid label, e.g. for a goto but not the default of the switch statement.

If you compile with gcc with enough warnings it will point this out:

ajw@rapunzel:/tmp > gcc -Wall -Wextra test.c
test.c: In function ‘main’: test.c:13:15: warning: label ‘defa1ut’ defined but not used

It's a good argument for building with warnings cranked up high and aiming for 0 warnings in every build.

like image 70
Flexo Avatar answered Dec 15 '22 06:12

Flexo


If defa1ut is a typo for default and the string "NONE" is printed:

This is because '1' and 1 is different.

'1' means the ASCII value of the character '1' whose value in decimal is 49. and 1 is an integer.

The first case will be true if the value of a is 49 or '1' , but as a=10 so it is neither equal to '1' nor equals to '2' and thus default is executed (if it existed, and defa1ut is not a typo).

If defa1ut is not a typo for default and simply nothing is printed:

In this case you have no default instead which look like it is defa1ut which will act as a normal label, so simply nothing will be printed.

like image 20
phoxis Avatar answered Dec 15 '22 04:12

phoxis