当前位置:网站首页>What happens when a function is called before it is declared in C?

What happens when a function is called before it is declared in C?

2022-07-01 03:37:00 Three Belle Wenzi

stay C in , If a function is called before it is declared , The compiler assumes that the return type of the function is int.
for example , The following program failed to compile .

#include <stdio.h>
int main(void)
{
    // Note that fun() is not declared
    printf("%c\n", fun());
    return 0;
}

char fun()
{
   return 'G';
}

Code compilation results :​​​​​​​

prog.c: In function 'main' in :
prog.c:5:17: Warning : function “fun” The implicit statement of  [-Wimplicit-function-declaration]
  printf("%c\n", fun());
                 ^
prog.c: On the top floor :
prog.c:9:6: error :“ Interesting ” Type conflict of 
  Character fun ()
      ^
prog.c:5:17: Be careful : Previously implied “fun” The statement is here 
  printf("%c\n", fun());

If the function in the above code char fun() Is in main() And defined after the call statement , Then it will not compile successfully . Because the compiler assumes by default that the return type is “int”. And in the declaration , If the return type is the same as int Mismatch , Then the compiler will give an error .

The following program is compiled and runs well , Because the function is in the main() As previously defined .​​​​​​​

#include <stdio.h>
 
int fun()
{
   return 10;
}
 
int main(void)
{
    // Note the function fun() is declared
    printf("%d\n", fun());
    return 0;
}

Output results :

10

What about parameters? ? The compiler makes no assumptions about parameters . therefore , When the function is applied to some parameters , The compiler will not be able to perform compile time checks for parameter types and quantities . This can lead to problems . for example , The following procedure is in GCC Compiled well , The garbage value is generated as output . ​​​​​​​

#include <stdio.h>
int main (void)
{
    printf("%d", sum(10, 5));
    return 0;
}
int sum (int b, int c, int a)
{
    return (a+b+c);
}

The compiler assumes that the input parameters are also int There is such a misunderstanding . If the compiler assumes that the input parameter is int, The above program cannot be compiled .
It is always recommended to declare a function before use , So we won't see anything unexpected when the program is running .

原网站

版权声明
本文为[Three Belle Wenzi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010318436818.html