Why does an empty declaration work for definitions with int arguments but not for float arguments?

二次信任 提交于 2019-11-27 12:13:44

A declaration:

int f();

...tells the compiler that some identifier (f, in this case) names a function, and tells it the return type of the function -- but does not specify the number or type(s) of parameter(s) that function is intended to receive.

A prototype:

int f(int, char);

...is otherwise similar, but also specifies the number/type of parameter(s) the function is intended to receive. If it takes no parameter, you use something like int f(void) to specify that (since leaving the parentheses empty is a declaration). A new-style function definition:

int f(int a, char b) { 
    // do stuff here...
}

...also acts as a prototype.

Without a prototype in scope, the compiler applies default promotions to arguments before calling the function. This means that any char or short it promoted to int, and any float is promoted to double. Therefore, if you declare (rather than prototype) a function, you do not want to specify any char, short or float parameter -- calling such a thing would/will give undefined behavior. With default flags, the compiler may well reject the code, since there's basically no way to use it correctly. You might be able to find some set of compiler flags that would get it to accept the code but it would be pretty pointless, since you can't use it anyway...

The declaration int fuc(float); tells the compiler that there exists a function fuc which takes a float and returns an int.

The definition int fuc(float f) { /*...*/ } tells the compiler what fuc actually is and also provides the declaration as well.

The difference between a declaration and definition is the difference between saying that a size 6 blue hat exists and and handing someone a size 6 blue hat: the declaration says that there is such a thing, the definition says that this thing right here is the thing in question.

prototype = forward declaration, so you can use it before you tell the compiler what it does. It still has parameters, however.

Useful in a lot of respects!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!