Why can I call a function in C without declaring it, but not in C ++?

In C ++, it is a compiler error to call a function before it is declared. But in C, it can compile.

#include<stdio.h>
int main()
{
   foo(); // foo() is called before its declaration/definition
} 

int foo()
{
   printf("Hello");
   return 0; 
} 

I tried and knew that this was correct, but I cannot understand the reason for this. Can someone explain how the compilation process really takes place and is different in both languages.

+4
source share
4 answers

The fact that the code is "compiled" as a c program does not mean that you can do it. The compiler must warn of an implicit function declaration foo().

In this particular case, the implicit declaration will be identical foo()and nothing bad will happen.

, :

main.c

/* Don't include any header, why would you include it if you don't
   need prototypes? */

int main(void)
{
    printf("%d\n", foo()); // Use "%d" because the compiler will
                           // implicitly declare `foo()` as
                           //
                           //              int foo()
                           //
                           // Using the "correct" specifier, would
                           // invoke undefined behavior "too".
    return 0;
}

, foo() 1 foo.c

foo.c

double foo()
{
    return 3.5;
}

, ?

, , malloc() stdio.h, , .

, undefined 2 "Works" .

, , , c, .

, 't ++, , ( "" ) .

c - undefined, , , , , .


1 , ,

2 , double int , - undefined .

+11

C , , , . ; , -, .

, C () . ++ : .

, , , ++ . , , , . , ( ?), .

, , , , , .

+5

C , ++ .

extern double atof();

, atof - , double. ( .)

double d = atof("1.3");

.

double d2 = atof();    /* whoops, forgot the argument to atof() */

, - , .

, , , , lint, C.

, , , :

int i = atoi("42");

,

extern int atoi();

, . , , , , , int.

. ++ , . , , , .

, C , . , , , , .

, C11. int, , . , , .

pre-C11, int. C11- ( ), . , C11, ints. (, clang, -Wno-implicit-int, , int, , .)

+2

C, ?

C, ++, , int.

. ( int), .

(, a int, , , , double, ), , . (, int foo() double foo() )

Please note that all this is only the C .
In C ++, implicit declarations are not allowed. Even if they were, the error message would be different, because C ++ has an overload function. An error will mean that function overloads cannot differ only in return type. (overloading occurs in the parameter list, and not in the inverse type)

+1
source

Source: https://habr.com/ru/post/1628540/


All Articles