Output of Nested printf and scanf in C [closed]

2019-09-26 07:56发布

问题:

Please help me with the output of this program. Why is it showing the result o/p PRINT 2 8 for input 3 4
I think the output can be different from machine to machine, but how is that coming.

#include<stdio.h>
int main() {
    int i,a;
    printf("%d",printf("PRINT %d\t",scanf("%d%d,",&i,&a)));  
    return 1;
}

回答1:

I think what you are missing is, your one line with nested function calls is basically same as this code:

int scanf_result = scanf("%d%d,",&i,&a);
int printf_result = printf("PRINT %d\t", scanf_result));
printf("%d", printf_result);

scanf call should return 2 if you entered valid input, but can also return -1 for actual error, or 0 or 1 if it failed to scan 2 integers. This is then printed by first printf as you'd expect, and it should return 8 (or 9 if scanf returned -1), so that 7 probably means difference between code you actually executed, and code you pasted... Then 2nd printf prints that number on the same line (no newline printed anywhere), giving you the final output.

There is no ambiguity, compiler can't do things in different order here. When you pass return value of a function as argument to another function, the first function has to be called first, to get the return value. So any "side-effects" such as reading from standard input or printing to standard output also happen in that order.

The way you can get ambiquity is to use assignment operators or ++ or -- operators multiple times on same variables inside same argument list. Then it is undefined when variable values actually change, and therefore which values get passed, when you use that same variable many times inside same argument list.



回答2:

printf() performs immediate output. It does not "return" the string you just printed. It returns how many characters were output (your 7). if you want the inner print to be fed to the outer one, you need to use sprintf() instead. "String printf".



回答3:

Any good C reference, such as the Linux printf and scanf manual pages, will document the return value for standard functions such as those, which will explain what you'll see when you print out their return values.

In this specific case, the return value for scanf is the number of input items successfully matched. Each "input item" corresponds to a % pattern in the scanf string, so in this case it will return 2 if scanf had valid input for both patterns. Then, printf returns the number of characters that it output. (In this case, the reported output is surprising, since I would expect 8: strlen("PRINT ") == 6, plus one character for the scanf return plus one more for the tab.)

I see no reason why either of those values would change from system to system, although of course it will change if scanf wasn't able to match both of its input items.



标签: c printf scanf