What happens if we include header file for two times in a C program?


C header files include some predefined functions. For example, printf() and scanf() functions are defined in the stdio.h header file.

  • Each header files in C contains different predefined functions to make programs simple to understand.

  • When a header file is included two times in a C program, the second one gets ignored. In actual, the #, called the include, preceding a header file ensures that it is included only once during the compilation process.

Example 1

Following is the C program for computing an average of three numbers −

 Live Demo

#include<stdio.h>
#include<stdio.h> //header file included twice ,ignored by compiler
main(){
   int a,b,c,d;
   float avg;
   printf("Enter values for a,b,c:");
   scanf("%d%d%d",&a,&b,&c);
   d=a+b+c;
   avg=d/3;
   printf("Average avg=%f",avg);
}

Output

When the above program is executed, it produces the following result −

Enter values for a,b,c:3 3 3
Average avg=3.000000

Example 2

Consider another C program for header files −

 Live Demo

#include<stdio.h>
#include<stdio.h>
#include<stdlib.h>
#include<stdlib.h>
//header file included twice ,ignored by compiler
main(){
   int a,b,c;
   printf("Enter values for a,b:");
   scanf("%d%d",&a,&b);
   c=a+b;
   printf("sum=%d",c);
}

Output

When the above program is executed, it produces the following result −

Enter values for a,b:2 4
sum=6

Updated on: 11-Mar-2021

877 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements