lord_jzb
lord_jzb

Reputation: 21

Program compiles and executes without header files turbo c++

I'm a noob in programming. My teacher compiled a program without any pre-processor directive at all and it executed and displayed output. It was just a hello world program. I'm confused that without the directives how it was able to carry out the "printf" function.

Upvotes: 2

Views: 195

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320551

In "classic" ANSI C (C89/90) you can call non-variadic functions without pre-declaring them, as long as you are careful about supplying arguments of proper type. So, if one does everything properly, one can write a formally valid C89/90 program that does not include any standard headers. E.g.

int main()
{
  puts("Hello World");
  return 0;
}

In modern C that would not be possible, since starting from C99 all functions have to be declared before being called.

Now, calling printf without pre-declaring it (with prototype) caused undefined behavior even in C89/90, since printf is a variadic function. So, if your teacher did something like that

int main()
{
  printf("Hello World\n");
  return 0;
}

then he/she still has a lot to learn about C. This C89/90 program is not valid, even if it compiled, executed and displayed output that "looked fine" to you.

However, you can still pre-declare the function manually

​int printf(const char *format, ...);​

int main()
{
  printf("Hello World\n");
  return 0;
}

and end up with a valid C89/90 program that does not use any preprocessing directives. Doing it that way is not a good programming practice though.

Upvotes: 3

Related Questions