c - void(*) void 和 int(*) int 在 C 中是什么意思?

标签 c pointers function-pointers declaration function-declaration

<分区>

谁能用C语言解释这两行代码:

void (*pfs)(void) = &fs;        
long int (*pfact)(int) = &fact; 

最佳答案

使这些声明更加清晰

void (*pfs)(void)=&fs;
long int (*pfact)(int)=&fact; 

您可以为函数声明引入 typedef 名称,例如

typedef void FUNC1( void );
typedef long int FUNC2( int );

然后写

FUNC1 *pfs = &fs;
FUNC2 *pfact = &fact; 

所以原始声明声明了指向指定类型函数的指针,并用给定函数的地址初始化它们。

这是一个演示程序

#include <stdio.h>

typedef void FUNC1( void );
typedef long int FUNC2( int );

void fs( void )
{
    puts( "Hello Islacine" );
}

long int fact( int x )
{
    return x;
}

int main(void) 
{
    FUNC1 *pfs = &fs;
    FUNC2 *pfact = &fact;

    pfs();

    printf( "sizeof( long int ) = %zu\n", sizeof( pfact( 0 ) ) );

    return 0;
}

它的输出可能看起来像

Hello Islacine
sizeof( long int ) = 8

考虑到这一点而不是

    FUNC1 *pfs = &fs;
    FUNC2 *pfact = &fact;

或代替

    void (*pfs)(void)=&fs;        
    long int (*pfact)(int)=&fact; 

你甚至可以写

    FUNC1 *pfs = fs;
    FUNC2 *pfact = fact;

    void (*pfs)(void) = fs;        
    long int (*pfact)(int) = fact; 

因为在极少数异常(exception)情况下,函数指示符会转换为指向函数的指针。

你甚至可以写:)

    FUNC1 *pfs = *****fs;
    FUNC2 *pfact = *****fact;

    void (*pfs)(void) = *****fs;        
    long int (*pfact)(int) = *****fact; 

来自 C 标准(6.3.2.1 左值、数组和函数指示符)

4 A function designator is an expression that has function type. Except when it is the operand of the sizeof operator65) or the unary & operator, a function designator with type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to function returning type’’.

关于c - void(*) void 和 int(*) int 在 C 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47422351/

相关文章:

c# - 嵌入式 C 中的 Modbus RTU 实现

c++ - 从一个类调用另一个类的成员函数

c++通用指针(成员?)函数

c - 如何减慢C中代码的执行速度?

c - 我有一个二叉搜索树,我想将节点复制到一个数组中序(递归函数)

c - 如何访问字符数组中的字符

c++ - 指向具有自定义结构的指针的指针

c++ - 使用 qsort() 时包含 C++ 字符串的类的排序不正确/错误

c - 引用超出结构大小的 malloc 字节

c++ - 如何给struct成员中的双指针赋值?