Use scanf in if statement

3.7k views Asked by At

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);  
}
3

There are 3 answers

0
ikegami On

You instructed scanf to read a signed integer. The input didn't even start with a sign or digit, so scanf didn't find a signed integers, so scanf returned 0 (the number of input items successfully matched and assigned), dropping you into the else clause of the if. Since scanf didn't match anything, it didn't assign anything, meaning a wasn't changed, and a-1 is 4.

You didn't specify what you were expecting, so I don't know what fix to suggest.

0
Vlad from Moscow On

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 unsignedand 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.

0
SHASHI BHUSAN On

In scanf() All the arguments you pass are pointers. There's no default-pro­mo­tion 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!