c - 为什么 func 看起来和 C 中的 &func 一样?

标签 c function pointers function-pointers implicit-conversion

<分区>

根据GNU C manual , 可以像这样使用函数指针调用函数:

func (j);  /* (*func) (j); would be equivalent. */

所以我的推理是:func 本身是指向 func(int) 函数的指针。当您调用 func(j) 时,您正在隐式访问指针 func 的值(您正在移动到 func 所在的内存位置),就像你有一个指向整数的指针一样,例如,你可以使用 * 访问存储在内存该位置的值。这与您可以使用 (*func)(j) 调用相同函数这一事实是一致的。

事实上,在cprogramming.com ,他们说你可以有一个指向函数指针的指针。因此,我猜测它们的工作方式与任何其他类型的指针一样。

但如果是这样,为什么这段代码有效?

#include <stdlib.h>
#include <stdio.h>

void a(int n) {
    printf("%d\n", num);
}

int main() {
    int x = 5;
    void (*func)(int); // Declare a pointer to a function
    func = &a; // Pointer to a pointer to a function
    (*func)(x); // Calls the function (why?)
    func = a; // Pointer to a function
    (*func)(x); // Calls the function (makes sense)
}

此外,如果你调用:

printf("%s\n", (&a == a) ? "True" : "False");

它打印True!

例如,我确定 &foo&&foo 不同,所以 为什么 func&func 一样吗?

最佳答案

N1570 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, the _Alignof operator,65) 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’’.

此处 a*func函数指示符,因为它们具有函数类型。 &a 中的 a 未转换为指针,因为它是一元 & 运算符的操作数,指向函数的指针由& 运算符。 另一方面,func = a;中的a根据这个规则转换为指向函数的指针。 因此这段代码中的a&a是等价的。

func(x);中的func也是按照这个规则转换为指针。

(*func)(x); 是:

  1. func按照这个规则转换为指针
  2. 指针被*func中的*解引用
  3. *func按照这个规则转换为指针

因此 (*func)(x); 等同于 func(x);

关于c - 为什么 func 看起来和 C 中的 &func 一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64718604/

相关文章:

c - 初始化指向结构体数组的指针数组

c - 检测到 glibc,realloc() : invalid old size C

javascript - 检查一个 javascript 是否已加载,然后调用另一个 javascript

function - 这个函数是如何工作的 : const const (negate 1) (negate 2) 3

c++ - C++中的手动内存管理

c - C 中的整数指针?

c - 为什么当你用字符串初始化一个没有 const 的数组时 gcc 不给出警告?

mysql - 存储函数返回 NULL Mysql

c++ - 我的 C 风格字符串表现得很奇怪

c - 我该如何解决这个递归溢出?