函数指针声明 [英] function pointer declaration

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

问题描述

说我有这个功能:

int func2()
{
    printf("func2\n");
    return 0;
}

现在我宣布一个指针:

int (*fp)(double);

这应该指向返回int和作为参数接收双重功能。
FUNC2没有任何参数,但仍当我写

This should point to a function that returns int and receives double as an argument. func2 does NOT have any arguments, but still when I write

fp = func2;
fp(2);

FUNC2正确调用。 2仅仅是一个随机数。
所以我的问题是 - 怎么回事?有没有意义的论点时,我宣布一个函数指针?
谢谢

func2 is invoked correctly. 2 is just a random number. So my question is - how is it? Is there no meaning to arguments when I declare a function pointer? Thanks

推荐答案

是的,有一个意思。在C(不过的的在C ++中),一组空括号声明的函数意味着它接受一个参数的未指定的数量。当你这样做,你是$ P $从检查参数的数量和类型pventing编译器;这是从之前的C语言被ANSI和ISO标准化的缓缴。

Yes, there is a meaning. In C (but not in C++), a function declared with an empty set of parentheses means it takes an unspecified number of parameters. When you do this, you're preventing the compiler from checking the number and types of arguments; it's a holdover from before the C language was standardized by ANSI and ISO.

未能与调用的参数导致的未定义行为的合适数量和类型的函数。如果不是明确声明你的函数使用无效的参数列表采取零参数,那么编译器会给你一个警告,当您分配了错误类型的函数指针

Failing to call a function with the proper number and types of arguments results in undefined behavior. If you instead explicitly declare your function to take zero parameters by using a parameter list of void, then the compiler will give you a warning when you assign a function pointer of the wrong type:

int func1();  // declare function taking unspecified parameters
int func2(void);  // declare function taking zero parameters
...
// No warning, since parameters are potentially compatible; calling will lead
// to undefined behavior
int (*fp1)(double) = func1;
...
// warning: assignment from incompatible pointer type
int (*fp2)(double) = func2;

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

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