我可以比较函数指针和函数的相等性吗?
Can I compare a function pointer to a function for equality?
这是有效的 C99 代码吗? (我想问的是便携)
void test(void){
return;
}
void (*fp)(void) = test;
if (fp == test){ <--- This line
printf("Success\n");
}
我收集到只有相同类型的指针可以相互比较,所以我的问题可能是像 'test' 这样的函数名称是否只是指针别名?或者也许有人可以告诉我我的问题比我更好:)
代码是有效的 ANSI C。
实际情况是,您代码中的函数名称(例如 test
)会自动转换为指向函数的指针。
你可以把test
改成&test
,结果是一样的。
是的,很好。在这种情况下,C 标准是不言自明的 (C11 6.3.2.1/4):
A function designator is an expression that has function type. Except when it is the
operand of the sizeof
operator, 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’’.
在你的例子中 test
是一个函数类型的表达式。它被转换为 void(*)(void)
类型的函数指针。这是与 fp
兼容的指针类型,因此 ==
运算符允许它。
关于相等运算符==
,标准说(C11 6.5.9,强调我的):
Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function,
这是有效的 C99 代码吗? (我想问的是便携)
void test(void){
return;
}
void (*fp)(void) = test;
if (fp == test){ <--- This line
printf("Success\n");
}
我收集到只有相同类型的指针可以相互比较,所以我的问题可能是像 'test' 这样的函数名称是否只是指针别名?或者也许有人可以告诉我我的问题比我更好:)
代码是有效的 ANSI C。
实际情况是,您代码中的函数名称(例如 test
)会自动转换为指向函数的指针。
你可以把test
改成&test
,结果是一样的。
是的,很好。在这种情况下,C 标准是不言自明的 (C11 6.3.2.1/4):
A function designator is an expression that has function type. Except when it is the operand of the
sizeof
operator, 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’’.
在你的例子中 test
是一个函数类型的表达式。它被转换为 void(*)(void)
类型的函数指针。这是与 fp
兼容的指针类型,因此 ==
运算符允许它。
关于相等运算符==
,标准说(C11 6.5.9,强调我的):
Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function,