原因输出 [英] Reason for the Output

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

问题描述

 #包括LT&;&stdio.h中GT;
INT主要(无效)
{
 INT 1 = 5;
 的printf(%d个+ 1,A);
}

输出:D。
我没有得到的输出是怎么来了?:D


解决方案

您为的printf %d个+1 <的第一个参数传递/ code>; %D实际上看作是为const char * 是指向一个内存位置%d个存储。正如任何指针,如果由一个增加它,结果将指向以下元件,其中,在这种情况下,将 D

A 不使用,但是这不应该是一个问题,因为一般(我不知道这是否是标准规定的 <千万b>编辑:的确是这样,见底部)可变参数函数的堆栈清理责任是由调用者(至少,的 cedcl 做这样的说法,但是这可能会或可能不会被UB,我不知道 *)。

您可以看到它更容易这种方式:

 #包括LT&;&stdio.h中GT;
INT主要(无效)
{
    INT 1 = 5;
    为const char *海峡=%D;
    的printf(STR + 1,a)的
}

&NBSP;

 海峡--------- +
             |
             V
          + ---- + ---- + ---- +
          | %|开发| \\ 0 |
          + ---- + ---- + ---- +STR + 1 + ----------
                  |
                  V
          + ---- + ---- + ---- +
          | %|开发| \\ 0 |
          + ---- + ---- + ---- +

因此​​,(%d个+1 )(即D)是间preTED作为格式字符串和的printf ,没有找到任何,将简单地打印出来,因为它是。如果你想,而不是打印 A 的值加1,你应该做的。

 的printf(%d个,一个+ 1);



修改
*好吧,它不是UB,至少在C99标准(§7.19.6.1.2)它的确定在未fprintf中的参数

如果在参数保持格式用完,多余的参数是
评估(一如既往),但否则将被忽略。

的printf 被定义为具有在§7.19.6.3.2相同的行为

printf函数等同于用fprintf中插入参数标准输出
在参数之前的printf。

#include<stdio.h>
int main(void)
{
 int a=5;
 printf("%d"+1,a);
}

Output: d. I didn't get how the output is coming: d ?

解决方案

You passed as first argument of printf "%d"+1; "%d" is actually seen as a const char * that points to a memory location where %d is stored. As with any pointer, if you increment it by one, the result will point to the following element, which, in this case, will be d.

a is not used, but this should not be a problem since in general (I don't know if it's standard-mandated Edit: yes it is, see bottom) the stack cleanup responsibility for variadic functions is up to the caller (at least, cedcl does it that way, this however may or may not be UB, I don't know*).

You can see it easier this way:

#include<stdio.h>
int main(void)
{
    int a=5;
    const char * str="%d";
    printf(str + 1, a);
}

 

str ---------+
             |
             V
          +----+----+----+
          |  % |  d | \0 |
          +----+----+----+

str + 1 ----------+
                  |
                  V
          +----+----+----+
          |  % |  d | \0 |
          +----+----+----+

Thus, ("%d"+1) (which is "d") is interpreted as the format string, and printf, not finding any %, will simply print it as it is. If you wanted instead to print the value of a plus 1, you should have done

printf("%d", a+1);


Edit: * ok, it's not UB, at least for the C99 standard (§7.19.6.1.2) it's ok to have unused parameters in fprintf:

If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored.

and printf is defined to have the same behavior at §7.19.6.3.2

The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.

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

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