2

I started using Visual Studio 2010 (c++) to code in C.

#include <stdio.h>
#include <stdlib.h>

int main(){
    printf("test");
    getch();
    return 0;
}

this code works, even without adding conio.h library and the program is paused right there, however getch(); is underlined and it says, that Error identifier getch(); is undefined.

How is that possible?

Prahalad Gaggar
  • 11,389
  • 16
  • 53
  • 71
tomdavies
  • 1,896
  • 5
  • 22
  • 32
  • 2
    Only guessing, but perhaps stdio.h pulls in (some parts of) conio.h? Technically, as long as the code is not using C++ features, you can use functions without declaring them (but you should enable warnings to avoid this). – Mats Petersson Apr 09 '13 at 10:17
  • I opened stdio and stdlib, crtl+f and searched for getch(), but there is only the original getchar()... – tomdavies Apr 09 '13 at 10:18
  • I bet both of those headers contain other includes tho'. – Mats Petersson Apr 09 '13 at 10:20
  • maybe it is a special function as in printf() which works when compiled with gcc without the stdio.h. even getch() works with gcc without any header – Koushik Shetty Apr 09 '13 at 10:22
  • "*... without adding conio.h library ...*" `conio.h` is **not** a library, but a header file providing (besides other things) prototypes to functions from a library. Libraries aren't used during compilation, but **after** compilation, that is during linkage. – alk Apr 09 '13 at 10:54

1 Answers1

10

The C language has a concept of "implicit declarations" for functions. If you don't provide a prototype, the compiler will assume the function was declared like:

int getch();

meaning that it is a function returning int that doesn't specify information about its parameters. Strictly speaking this is not an error, but many compilers will issue a warning if your warning level is set high enough. This behavior was removed in C99 onward, and you should generally avoid relying on it.

Since the library still provides the getch() function, there is no issue resolving its symbol at link time. As a result, and due to the fact that getch() actually does return an int, everything works out.

FatalError
  • 52,695
  • 14
  • 99
  • 116