它是可移植的定义和声明函数后调用它在main中的C? [英] Is it portable to define and declare the function after calling it in main in C?

查看:142
本文介绍了它是可移植的定义和声明函数后调用它在main中的C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了与C和C ++之间的函数定义/声明有关的以下差异。

I came across the following difference related to function definition/declaration between C and C++.

在C ++中,如果我在声明和定义函数之前调用函数,

In C++ if I call a function before declaring and defining it,I get the error message 'function name is invalid identifier' which is fine for me as it sounds reasonable.

在Visual Studio编译器的C中,当我编译下面的程序时,我得到了一个错误消息函数名是无效的标识符错误消息:

In C with Visual Studio compiler when I compiled the following program I get the error message:

error C2371: 'fun' : redefinition; different basic types

,在gcc-4.3.4中,它成功执行,只有这个警告:

and in gcc-4.3.4 it executed successfully with just this warning:

warning: conflicting types for ‘fun’

这里是程序:

#include <stdio.h>
int main(){
    fun();
    return 0;
}
void fun(){
    printf("It is fun");
}

所以在C中调用一个函数,它?!

So is it fine in C to just call a function and later bother about defining it?! And why the compilers behave differently?

推荐答案

在C89中调用没有原型的函数时(免责声明:我不知道关于C99),你隐式声明为

When you call the function without a prototype in C89 (disclaimer: I don't know about C99), you are implicitly declaring it as

int fun();

int fun();

除了在C ++中,空的parantheses只是意味着你没有指定它需要什么参数,而不是它需要零个参数。

Note that in C, other than in C++, the empty parantheses just mean that you haven't specified what arguments it takes, not that it takes zero arguments.

当你重新声明函数为返回void,你得到警告,但没有错误。如果你返回一些非平凡的(structs,float,...)而不是void或者如果你尝试使用函数的int结果,那么你可能在运行时遇到了麻烦。

When you redeclare the function as returning void, you get the warning, but no error. If you return something non-trivial (structs, floats, ...) instead of void or if you try to use the int result of the function, then you might be in deep trouble at runtime.

这篇关于它是可移植的定义和声明函数后调用它在main中的C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆