Qwertiy
Qwertiy

Reputation: 21400

Is it correct to drop #include <stdio.h> in C?

If I use printf, scanf, puts or some other function in C (not C++) and don't write an include line, can it be treated as unspecified or undefined behaviour?

As I remember, C didn't require porotope declaration at all, but it was recommended to have them to allow compiler to make type casts on calling. And prototypes for printf and other such functions are not required still, not sure about custom functions.

PS: This question relates to discussion in comments of https://codegolf.stackexchange.com/a/55989/32091.

Upvotes: 3

Views: 567

Answers (4)

peterh
peterh

Reputation: 1

For professional development, no.

For codegolfing, it is ok.

If you don't declare a function, the compiler automatically generates one, which may or may not match its real declaration. If it doesn't, it may or may not produce segfault or a software bug. gcc also gives in this case a warning.

Upvotes: 2

ouah
ouah

Reputation: 145839

Is it correct to drop #include in C?

No, it's not correct. Always include it if you use a stdio.h function like printf.

C has removed implicit declarations (with C99) and the includes are required. The only other alternative is to have a visible prototyped declaration for printf.

Moreover even when C had implicit declarations, implicit declarations are not OK for variable argument functions; so in C89 not adding a stdio.h include and not having a visible prototype (for printf example) is undefined behavior.

Upvotes: 2

Kiloreux
Kiloreux

Reputation: 2256

No and Yes

stdio.h has an explicit declaration of the functions you want to use, such things are prohibited if it was a C++ compiler (g++ for example). Since c++ requires explicit declarations of all functions, but any proper C compiler will create an implicit declaration of those functions, compile the code into object file, and when linked with the standard library, it will find a definition of those functions that accidentally will match the implicit declaration, probably gcc will give you a warning.

So if you are writing software that you want to be maintainable and readable, that's not an option to drop it, however for fast prototyping or code challenges, this might not be that important.

Upvotes: 1

i486
i486

Reputation: 6563

Technically you can skip #include in many cases. But for some functions the compiler cannot generate correct function call without prototype. E.g. if a parameter is double and you put 0 - with prototype it will be converted and stored as double value in stack and otherwise there will be int which will produce wrong calculations.

Upvotes: 0

Related Questions