Omkant
Omkant

Reputation: 9204

What type of behaviour is this?

This question is looking for a standardese quote explicitly explaining why this behavior is wrong.

The code below including <stdio.h> inside main ,

int main()
{
 #include <stdio.h>
 printf("hello , world \n");
 return 0;
}

On gcc -Wall in.c -o in.out It successfully compiles and prints hello , world.

But on clang in.c -o in.out It gives me this error :

/usr/include/stdio.h:353:12: error: implicit declaration of 'fprintf' requires 

inclusion of the header <stdio.h>
extern int fprintf (FILE *__restrict __stream,
           ^
1 error generated.

My doubt is what kind of behaviour is this ? Is this undefined behaviour or what ?

Also I am not able to find the documentation related to it.

EDIT : The problem is that I found this code somewhere similar to it but I can't post that code exactly so I posted this kind of Demo code.I know the Placing stdio.h outside the main.

Upvotes: 0

Views: 161

Answers (3)

melpomene
melpomene

Reputation: 85767

C99, 7.1.2/4:

[...] If used, a header shall be included outside of any external declaration or definition, and it shall first be included before the first reference to any of the functions or objects it declares, or to any of the types or macros it defines.

4/2:

If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint is violated, the behavior is undefined.

6.9/4:

As discussed in 5.1.1.1, the unit of program text after preprocessing is a translation unit, which consists of a sequence of external declarations. These are described as ‘‘external’’ because they appear outside any function (and hence have file scope).

So I think this is undefined behavior.

Upvotes: 5

Tony Delroy
Tony Delroy

Reputation: 106096

In C++11: 17.6.2.2/3:

A translation unit shall include a header only outside of any external declaration or definition, and shall include the header lexically before the first reference in that translation unit to any of the entities declared in that header.

main() is extern, so is not a proper context for include.

Upvotes: 2

Jim Las
Jim Las

Reputation: 25

Try including the header file outside of the main method. Like this.

#include <stdio.h>
int main()
{
 printf("hello , world \n");
 return 0;
}

Upvotes: -2

Related Questions