Why the output is '4' ? , while input is 'A'
int main() { int a = 5;
if(scanf("%d",&a))
printf("%d",a+1);
else
printf("%d",a-1);
}
Why the output is '4' ? , while input is 'A'
int main() { int a = 5;
if(scanf("%d",&a))
printf("%d",a+1);
else
printf("%d",a-1);
}
When type sepcifier %d
is used then the function expects that a valid signed decimal integer number will be entered. It is evident that symbol 'A'
is not a number so the input failed.
Now a question arises: what will the function return in this case?
According to the description of function scanf
(the C Standard, 7.21.6.4 The scanf function):
3 The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
So the condition in the if statement
if(scanf("%d",&a))
evaluated to 0 (false) and the else statement was executed.
else
printf("%d",a-1);
that outputed 4.
Take into account that in general you may enter symbol 'A'
for integers. But in this case the corresponding integer variable must be declared as unsigned
and format specifier of scanf
must to be %x
For example
#include <stdio.h>
int main( void )
{
unsigned int a = 5;
if ( scanf( "%x", &a ) )
{
printf( "%u\n", a + 1 );
}
else
{
printf( "%u\n", a - 1 );
}
}
In this case the output will be 11
.:) scanf
will consider symbol 'A'
as a hexadecimal representation of 10.
In scanf() All the arguments you pass are pointers. There's no default-promotion among pointers, and it is crucial that you pass the exact format specifier that matches the type of the pointer.
for more clearance:- Click here!
You instructed
scanf
to read a signed integer. The input didn't even start with a sign or digit, soscanf
didn't find a signed integers, soscanf
returned0
(the number of input items successfully matched and assigned), dropping you into theelse
clause of theif
. Sincescanf
didn't match anything, it didn't assign anything, meaninga
wasn't changed, anda-1
is4
.You didn't specify what you were expecting, so I don't know what fix to suggest.