使用嵌套的printf语句给人奇怪的输出 [英] using nested printf statements giving strange output

查看:133
本文介绍了使用嵌套的printf语句给人奇怪的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我遇到了这个code和我无法理解它是如何工作的。

 #包括LT&;&stdio.h中GT;
诠释主(){
    的printf(1号线\\ n
    的printf(2号线\\ n
    的printf(3号线\\ n
    的printf(4号线\\ n
    0))));
返回0;
}

这是给下面的输出:

  4号线
3号线
2号线
1号线


解决方案

的printf 用于打印格式化的线。例如,要打印一个整数,你可以调用:

 的printf(%d个,1);

你做了什么,是嵌套的打印的返回值作为参数,这意味着它首先需要评估嵌套调用调用它。您的来电是类似于:

  INT温度;
TEMP =的printf(4号线\\ n,0);
TEMP =的printf(3号线\\ n,温度);
TEMP =的printf(2号线\\ n,温度);
TEMP =的printf(1号线\\ n,温度);

另外请注意,因为你必须在格式字符串没有格式说明,也没有意义,第二个参数,如果你的编译器是不够好它甚至会警告你。

I recently came across this code and I'm unable to understand how it works

#include<stdio.h>
int main(){
    printf("Line 1\n",
    printf("Line 2\n",
    printf("Line 3\n",
    printf("Line 4\n",
    0))));
return 0;
}

It is giving the following output:

Line 4
Line 3
Line 2
Line 1

解决方案

printf is used to print a formatted line. For example, to print an integer, you call:

printf( "%d", 1 );

What you did, is call it with the return value of the nested print as argument, which means that it first need to evaluate the nested call. Your call is similar to:

int temp;
temp = printf("Line 4\n", 0);
temp = printf("Line 3\n", temp);
temp = printf("Line 2\n", temp);
temp = printf("Line 1\n", temp);

Also, note that since you have no format specifiers in the format string, there is no meaning to the second argument, and if your compiler is nice enough it will even warn you about that.

这篇关于使用嵌套的printf语句给人奇怪的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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