+2

Can anyone explain why this code returns 1 on every input?

#include <stdio.h> int main() { int a; printf("%d", scanf("%d", &a)); return 0; } But in option -1 is the answer how -1 will be the answer

10/20/2019 3:35:00 AM

Preity

6 Answers

New Answer

+5

scanf returns the number of input items read and matched(to format specifier) and assigned successfully to the argument passed. Returns 0 if conversion fails and -1(EOF) if the input stream ends abruptly or there is some error (but note if scanf has read some inputs successfully before the input stream ends abruptly or forcefully or due to some error, or if the conversion fails then scanf returns the number of inputs read successfully till that point). You can confirm this by adding another "%d", and argument. e.g. printf("%d", scanf("%d %d", &a, &a)); This also implies that the return value can be less than the number of input specified. Like this is happening now or when the conversion fails or the input stream ends abruptly or EOF encountered for whatever reasons.

+2

Quoting http://www.cplusplus.com/reference/cstdio/scanf/ "On success, the function returns the number of items of the argument list successfully filled." In your case, scanf() fills one item in the argument list, and returns 1.

+2

Preity Yes that is correct for the example provided.

0

~ swim ~

0

As scanf returns the number of conversions that were successfully made, the example program will either print a 1, a 0 or a -1, depending on the provided input (1 if the start of the input is convertible to an integer, 0 for non-integer input, -1 for input errors).

0

Does that too an case or any other explanation for that behavior