Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn’t putchar require a header?

Tags:

c

Reading this answer which explains the polyglot program on page not found on Stack Overflow I was surprised to read putchar was used because you don't need any #include to use it. This seems to be the case, although en.cppreference.com reference and www.cplusplus.com reference show putchar as defined in the stdio.h header.

How can a function be used (correctly) without having a declaration in C? Or is putchar something inbuilt in compiler (like sizeof operator)?

like image 502
bolov Avatar asked Jul 29 '26 12:07

bolov


2 Answers

In c, you can use any function without a declaration.

The compiler then assumes, that the function has a return type of int. The parameters are passed to the function as given. Since there is no function declaration, the compiler cannot verify, if the parameters are correct.

putchar is not builtin into the compiler. However, since

The function call putchar(c) shall be equivalent to putc(c,stdout).

it might be defined as a macro, e.g.

#define putchar(c) putc(c, stdout)

In this case, you must include stdio.h to have the correct definition for putchar.

like image 163
Olaf Dietsche Avatar answered Aug 01 '26 01:08

Olaf Dietsche


Some compilers do weird, non-standard things such as automatically including various common headers. It is possible that the code was compiled on one such compiler.

Otherwise, in the old obsolete C90 standard, you didn't need to have a function prototype visible: if you had not, the compiler would start to assume that the return type was int. Which doesn't make any sense. This nonsense was removed from the C language with the C99 standard.

So the reason the code compiled, was because you used a crappy compiler. There are no guarantees that the code will compile/link or work as predicted.

For example:

int main ()
{
  putchar('a');
}

This compiles with gcc as well as gcc -std=c90. But if you compile it as standard C,

gcc -std=c99 -pedantic-errors

you'll get error: implicit declaration of function 'putchar'.

like image 31
Lundin Avatar answered Aug 01 '26 01:08

Lundin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!