5

Possible Duplicate:
Why #include <stdio.h> is not required to use printf()?

//#include <stdio.h>
//#include <conio.h>

main(){

printf("Hi");
getch();

}

As I was programming this, it shocked me that it worked without actually importing any c libraries such as stdio that contains the printf function. Why is that so? (Used Dev-C++ 4.9.9.2, saved as .c, not .cpp)

Community
  • 1
  • 1
Xegara
  • 563
  • 2
  • 10
  • 23

2 Answers2

8

C allows you to call functions without first defining the prototypes. (C++ does not do this.) An implicit prototype for printf will be defined as follows:

int printf();

Coincidentally, the calling conventions for this implicit prototype matched the actual calling conventions for printf on your platform.

In general, you cannot count on this working, and there are a large number of cases where it won't work. I recommend enabling compiler warnings to detect implicit prototype declarations so you can fix them (by including the correct header).

Footnote: #include does not import libraries, it merely pastes files into your source code at compile time. The <stdio.h> header contains (directly or indirectly) certain prototypes, but the library has to be linked in separately. Since printf is usually in a library that is linked to programs by default, you usually don't have to do anything to use printf.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • Yes and no. For C89/90 the program will normally "compile". But remember that `printf` is a *variadic* function. Calling a variadic function without a prototype leads to *undefined behavior*. In that sense, C language does not really "allow" one to call `printf` without a prototype. Of course, C99 language will not even compile a call to an undeclared function. – AnT stands with Russia Jun 22 '12 at 06:51
  • @AndreyT: Yes, that's why I said "coincidentally ... on your platform", and "you cannot count on this working". – Dietrich Epp Jun 22 '12 at 06:55
4

The #include preprocessor directive does not import any library; there is no such notion of import in the definition of the C language.

You just happen to call a function named printf and the standard C library (e.g. libc.so on Linux, I don't know how Windows call it) happens to be linked in by default. Since you call a function by a name known to that library, it gets linked, and is being called at runtime.

However, you should enable all warnings in you compiler, and it would warn that you call an undeclared function.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547