<分区>
谁能用C语言解释这两行代码:
void (*pfs)(void) = &fs;
long int (*pfact)(int) = &fact;
<分区>
谁能用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/