Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit function declarations in C

Tags:

c

What is meant by the term "implicit declaration of a function"? A call to a standard library function without including the appropriate header file produces a warning as in the case of:

int main(){   printf("How is this not an error?");   return 0; } 

Shouldn't using a function without declaring it be an error? Please explain in detail. I searched this site and found similar questions, but could not find a definitive answer. Most answers said something about including the header file to get rid of the warning, but I want to know how this is not an error.

like image 933
Bazooka Avatar asked Feb 07 '12 19:02

Bazooka


People also ask

What is implicit declaration of function error in C with example?

This error occurs because you are trying to use a function that the compiler does not understand. If the function you are trying to use is predefined in C language, just include a header file associated with the implicit function.

What is implicit variable declaration?

Implicit variable declaration means the type of the variable is assumed by the operators, but any data can be put in it. In C, int x = 5; printf(x-5); x = "test"; printf(x-5); returns a compile time error when you set x to test.

How is a function declared in C language?

In C and C++, functions must be declared before the are used. You can declare a function by providing its return value, name, and the types for its arguments. The names of the arguments are optional. A function definition counts as a function declaration.

What is implicit declaration of function getch?

Prior to the C99 standard, the C language permitted calls to functions with no visible declaration. Such a call would in effect create an implicit declaration of a function returning int and taking arguments of whatever (promoted) type you actually passed. Depending on this has never been a good idea.


1 Answers

It should be considered an error. But C is an ancient language, so it's only a warning.
Compiling with -Werror (gcc) fixes this problem.

When C doesn't find a declaration, it assumes this implicit declaration: int f();, which means the function can receive whatever you give it, and returns an integer. If this happens to be close enough (and in case of printf, it is), then things can work. In some cases (e.g. the function actually returns a pointer, and pointers are larger than ints), it may cause real trouble.

Note that this was fixed in newer C standards (C99, C11). In these standards, this is an error. However, gcc doesn't implement these standards by default, so you still get the warning.

like image 88
ugoren Avatar answered Sep 19 '22 06:09

ugoren