C 中嵌套 printf 和 scanf 的输出 [英] Output of Nested printf and scanf in C

查看:112
本文介绍了C 中嵌套 printf 和 scanf 的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我看看这个程序的输出.为什么显示结果o/p PRINT 2 8 用于输入 3 4
我认为输出可能因机器而异,但这是如何产生的.

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

推荐答案

我认为您缺少的是,您的一行嵌套函数调用与此代码基本相同:

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 调用应该返回 2 如果你输入了有效的输入,但也可以返回 -1 表示实际错误,或者 0 或 1 如果它无法扫描 2 个整数.然后按照您的预期由第一个 printf 打印,它应该返回 8(如果 scanf 返回 -1,则返回 9),因此 7 可能意味着代码之间的差异您实际执行了,并粘贴了代码...然后第二个 printf 在同一行上打印该数字(任何地方都没有打印换行符),为您提供最终输出.

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.

这篇关于C 中嵌套 printf 和 scanf 的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆