+ 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

20th Oct 2019, 3:35 AM
Preity
Preity - avatar
4 ответов
+ 3
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.
20th Oct 2019, 3:54 AM
Hatsy Rei
Hatsy Rei - avatar
20th Oct 2019, 3:36 AM
Preity
Preity - avatar
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).
20th Oct 2019, 4:09 AM
Preity
Preity - avatar
0
Does that too an case or any other explanation for that behavior
20th Oct 2019, 4:09 AM
Preity
Preity - avatar