可以得到的printf在C程序会自动将取代? [英] Can printf get replaced by puts automatically in a C program?

查看:135
本文介绍了可以得到的printf在C程序会自动将取代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int puts(const char* str)
{
    return printf("Hiya!\n");
}

int main()
{
    printf("Hello world.\n");
    return 0;
}

这code输出你好!当运行。可能有人解释为什么?

This code outputs "Hiya!" when run. Could someone explain why?

编译行是:
GCC的main.c

编辑:它现在是纯C,任何多余的东西已经从编译行删除

it's now pure C, and any extraneous stuff has been removed from the compile line.

推荐答案

是,编译器可通过替换为的printf 调用的相当于的来电看跌

Yes, a compiler may replace a call to printf by an equivalent call to puts.

由于您定义自己的函数看跌具有相同名称作为标准库函数,你的程序的行为是不确定的。

Because you defined your own function puts with the same name as a standard library function, your program's behavior is undefined.

参考: N1570 7.1.3:

在任一下列条款与外部链接的所有标识符[这包括看跌]总是保留用作与外部连接的标识符。结果
   ... 结果
  如果程序声明或在一个限定的标识符
  上下文中它被保留(比其它由7.1.4所允许),或限定一个保留
  标识为宏名,行为是不确定的。

All identifiers with external linkage in any of the following subclauses [this includes puts] are always reserved for use as identifiers with external linkage.
...
If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.

如果您删除自己的看跌函数,检查装配上市,你的可能的找到使通话在生成的code,你在源$ C ​​$ C名为的printf 。 (我见过的gcc执行这个特别的优化。)

If you remove your own puts function and examine an assembly listing, you might find a call to puts in the generated code where you called printf in the source code. (I've seen gcc perform this particular optimization.)

这篇关于可以得到的printf在C程序会自动将取代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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