C语言函数 [英] C prototype functions

查看:135
本文介绍了C语言函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个初学者到C,我可以理解为在该文件中的函数原型的需要,但我不能确定的两件事情。

As a beginner to C, I can understand the need for function prototypes in the file, but am unsure of a couple things.

首先,它的主要之外每个函数调用需要一个原型声明?是否有任何条件的地方,可以改变?

First, does every function call outside of the main require a prototype declaration? Are there any conditions where that can change?

其次,你需要一个单独的函数原型方法重载?

Second, do you need a separate function prototype for method overloads?

推荐答案

功能的C调用不需要原型是可见的,但强烈建议正确的原型是在范围内。

Function calls in C don't require a prototype to be visible but it is highly recommended that a correct prototype is in scope.

这样做的理由是,如果执行默认的功能参数提升后的函数定义不匹配类型的函数参数就非常可能得到未定义的行为。

The reason for this is that if the function definition doesn't match the types of the function arguments after the default function argument promotions are performed you are highly likely to get undefined behavior.

具有正确的原型可见意味着编译器可以检查一个函数调用的参数并警告程序员,如果有一个不匹配。

Having the correct prototype visible means that the compiler can check the arguments of a function call and warn the programmer if there is a mismatch.

C不容许函数重载,所以你只能有一个原型的函数名。

C doesn't allow functions to be overloaded so you can only have a single prototype for any function name.

默认参数提升可能会导致意外的不匹配。

Default argument promotions can cause unexpected mismatches.

例如

int main(int argc, char **argv)
{
    short s = 5;
    float f = 2.3f;
    x(s, f);     // x implicitly declared; default argument promotions performed
    return 0;
}

int x(short t, float g)  // Error: called with an int and a double
{
    return (int)(t + g);
}

在函数调用,因为 X 是不可见的原型(还),取值将晋升为 INT ˚F将晋升为双击。这些都是的默认参数提升的。然后,这会导致不匹配时,该函数与原型,需要定义一个浮动尽管这些都是原来类型的被传递的参数。

In the function call, because x has no visible prototype (yet), s will be promoted to int and f will be promoted to double. These are default argument promotions. This then causes a mismatch when the function is defined with a prototype that takes a short and a float even though these are the original types of the arguments that were passed in.

这是带有可变数量的参数的函数(即使用 ... 语法)必须始终拥有在他们被称为点可见雏形。

Functions that take a variable number of arguments (i.e. use , ... syntax) must always have a visible prototype at the point at which they are called.

这篇关于C语言函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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