C函数的定义和声明 [英] C function definition and declaration

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

问题描述

我是一个Java程序员,我学过一点C ++,现在我学习我的工作有点℃。
我不明白有关函数声明/定义以及相关的函数调用C行为。
从K&安培; R我知道,在C(从C截然不同++)我可以调用一直没有pviously宣布$ P $的函数,编译器假定类型的隐式声明:

I'm a Java programmer,I learnt a little C++ and now I'm studying a little C for my job. I can't understand C behaviour about function declaration/definition and related function calls. From K&R I know that in C (very different from C++) I can call a function that has not been previously declared,and the compiler assumes an implicit declaration of the type:

int main() 
{
  function(10);   // implicit function declaration ( int function() )
}

和我知道,这样的声明意味着接受任何类型的参数固定,但数目不定的功能(只要每个呼叫与他人一致)。我知道这是K&安培; R C,C89过,但我想知道它是如何工作为好。
现在,我有这个测试code,我不明白:

and I know that such a declaration implies a function that accepts a fixed but indefinite number of arguments of any type (as long as each call is consistent with the others). And I know this is K&R C, before C89, but I want to know how it works as well. Now, I have this test code, I can't understand:

#include <stdio.h>

function();

int main()
{
  printf("hello %d",function(1,2,3));
  implicit(11,12,32);     // implicit function declaration ( implicit() )
}


int implicit(int b)
{

}

function(int a)
{

}

函数的情况下,声明(返回类型被假定为int,没有关于参数的假设),不符合定义(编译器会发出警告),但如果我调用该函数使用了错误的参数,它编译!
同为功能
我无法理解。

in the case of function the declaration (return type is assumed to be int,no assumption about the arguments) does match the definition (the compiler issues a warning) but if I call the function with the wrong arguments,it compiles! Same for the function implicit. I can't understand..

推荐答案

你要记住的事情是,编译为pretty多少的顺序,当涉及到的声明和定义。当编译器处理的要求函数所有它是这样的,就像你说的,没有关于参数的任何假设的声明,这意味着你可以调用函数与任何参数,你喜欢的。当编译器看到的定义,不回去发出有关调用一个错误,它可能会虽然发出警告。

The thing you have to remember is that the compile is pretty much sequential when it comes to declarations and definition. When the compiler processes the call for function all it has is the declaration that, as you say, doesn't have any assumptions about the arguments, which means you can call the function with any argument you like. When the compiler sees the definition, it doesn't go back to issue an error about the call, it might issue a warning though.

对于功能,当编译器第一次看到它,它会假设参数是您在通电话的时候是什么推导出的声明。同样也不会知道任何东西,直到后来看到声明,可能会发出警告呢。

As for the implicit function, when the compiler first sees it it will assume that the arguments are what you pass in the call when it deduces the declaration. Again it will not know anything else until it later sees the declaration, and may issue a warning then.

调用带有很多功能,还是要少,参数导致的未定义行为的,这就是为什么隐含声明的功能是如此的危险,以及声明函数时使用空参数列表。

Calling a function with to many, or to few, arguments leads to undefined behavior, which is why implicitly declared functions are so dangerous, as well as using an empty argument list when declaring functions.

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

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