Can printf get replaced by puts automatically in a C program?

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.

Reference: N1570 7.1.3:

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.

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.)

Leave a Comment