C Programming - Library Functions - Discussion

3. 

What will be the output of the program?

#include<stdio.h>

int main()
{
    int i;
    i = scanf("%d %d", &i, &i);
    printf("%d\n", i);
    return 0;
}

[A]. 1
[B]. 2
[C]. Garbage value
[D]. Error: cannot assign scanf to variable

Answer: Option B

Explanation:

scanf() returns the number of variables to which you are provding the input.

i = scanf("%d %d", &i, &i); Here Scanf() returns 2. So i = 2.

printf("%d\n", i); Here it prints 2.


Ravi said: (Aug 17, 2011)  
How this works?

Vasantha Deepika said: (Aug 27, 2012)  
Can any explain in detail how does it works?

Akanksha Jain said: (May 9, 2013)  
Could you please explain how its throwing output as 2, when I ran this in gcc compiler(32 bit) which is provided here, it was throwing output as "-1"?

Sachin said: (Jul 12, 2014)  
How this works?

Maneesh Singh said: (Jul 30, 2014)  
scanf is also a function and it has a return type so whenever you call any scanf function in printf it gives you return value either 1 or 0. 1 means success and 0 means fail. for ex -

int a=10, b= 20;
printf("%d", add(a, b));

int add(int x, int y)
{
return (x+y);
}

In this ex printf will print return value of add fn that is 30..same way scanf will print its return value if success then 1 else 0...

Try this:

int d =0;
printf("d= %d, d1 = %d, d2 = %d\n", d, scanf("%d", &d), d);

Bilal said: (Sep 18, 2014)  
When you write scanf() it awaits for an input, why would you get get 2 as output when the input is not even entered?

Arungv said: (Nov 5, 2014)  
#include<stdio.h>

int main()

{
int i;
i = scanf("%d %d", &i, &i);
printf("%d\n", i);
return 0;
}

Output is -1(this only i got ) in 32 Linux platform.

Amit Shrivastav said: (Aug 15, 2016)  
The output is -1, let me correct or explain how I got output a is -1.

Raman said: (Apr 14, 2018)  
Can anybody explain in detail?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.