You are here:

C/header files

Advertisement


Question
if i save my program with .c extension, my program run successfully with printf(), scanf(), getch(), clrscr() without including header file <stdio.h> and <conio.h> but this do not work with other header files such as <math.h> etc. They need to be included. Why?


Answer
Hello Ajay.

If the correct header files are not included, the C compiler will make assumptions about the functions you are calling. Compilers differ in how they handle missing function prototypes, but generally you don't want assumptions made about your code.

Here is a test program.

int main(void)
{
   int i;
   printf("Hello\n");
   i = atof("123.456");
}

The Microsoft compiler (version 2003) gives me warnings by default:
warning C4013: 'printf' undefined; assuming extern returning int
warning C4013: 'atof' undefined; assuming extern returning int

Of course we all know that atof should return a double (8 bytes), not an int (4 bytes), so who knows what bad things might happen with the stack when this is executed.

The gcc compiler is silent about the missing header files unless you turn on all warnings. Then it says
$ gcc -Wall lw.c
lw.c: In function `main':
lw.c:4: warning: implicit declaration of function `printf'
lw.c:5: warning: implicit declaration of function `abs'
lw.c:6: warning: control reaches end of non-void function

You can see why warnings are important and should never be ignored.

Your compiler might be different. Compilers behave according to the ideas of their developers which may be different form the standard. Just because a compiler accepts something doesn't make it correct. I would not trust a compiler that cannot warn me about missing function prototypes.

When programming, turn on all warnings. Include all necessary header files. They help the compiler check that you are calling the functions correctly. Use up-to-date compilers if possible. If possible, compile your code with multiple compilers.

Best regards
Zlatko

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.