Reputation: 89
What will be the output of the following code?
#include <stdio.h>
int n;
int main() {
scanf("&d", &n);
switch (n) {
case 1:
printf("hello\n");
break;
case 2:
printf("good\n");
break;
default:
printf("Morning\n");
break;
}
return 0;
}
Most people expected there to be an error but on execution it always outputs Morning
no matter what input is given.
Upvotes: 0
Views: 565
Reputation: 85767
The output will always be Morning
.
scanf("&d")
expects as input the two characters &
and d
, literally. If you type anything else, the scanf
call will fail. However, your code doesn't check the return value of scanf
, so it makes no difference.
The &n
argument to scanf
is ignored because there is no "conversion specification" (those are the things starting with %
) in the format string. Thus (as the C standard says (C99, 7.19.6.2 The fscanf
function / 2)):
If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored.
scanf("&d", &n)
is therefore equivalent to just scanf("&d")
.
When switch (n)
examines n
, it will still contain the value it was initialized with. There is no explicit initializer, so it is set to 0
(because it's a global variable (specifically, because it has static storage; see C99, 6.7.8 Initialization / 10)).
There is no case 0:
label, so default:
kicks in.
Upvotes: 6
Reputation: 180171
"Morning" is the correct output for this program.
In the first place, there is no reason to expect an error message, because the program does not anywhere print one. In particular, C standard library functions such as scanf()
do not emit error messages to the standard streams. Instead, they return status information via their return values, and in some cases by setting the thread-local variable errno
. This program does not even check the return value of scanf
, so there is no reason to think that it will emit an error message on account of any problem there.
Secondly, although the format string passed to scanf
appears to contain a typo, it is still a perfectly valid format. It tells scanf
to attempt to read (but do nothing else with) the two-character sequence "&d". If those are not the next two characters it sees, then it will fail with a matching error, which it will indicate by returning 0. In fact, it will also return 0 if those are the next two characters, because the return value communicates the number of input fields successfully scanned, converted, and stored, and the format does not describe any input fields.
The second scanf
argument is ignored in all cases, but some compilers will emit a warning (not an error) about it.
Since scanf
does not assign a value to variable n
, it retains whatever value it had before the call. Since it was declared at file scope, it is automatically initialized to zero before the start of the program, and it still has this value when exectution reaches the switch
statement. This results in the default case being exercised.
Upvotes: 3