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;
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With