为什么 typedef void (*f_ptr)(int);和 typedef void (*f_ptr)();在 C 中工作一样吗?

why typedef void (*f_ptr)(int); and typedef void (*f_ptr)(); work the same in C?

我在定义函数指针时不小心忘了加上(int),我的程序仍然运行。 我想知道是否有任何情况下它不起作用。 我的代码:

#include <stdio.h>

void f1(int var)
{
    printf("this is f1 and var is: %d\n", var);
}

void f2(int var)
{
    printf("this is f2 and var is: %d\n", var);
}

void f3(int var)
{
    printf("this is f3 and var is: %d\n", var);
}
typedef void (*f_ptr)(int);
// pq eu poderia escrever: typedef void (*f_ptr)(); e o programa funcionaria normalmente?
typedef int n_casa;

int main()
{
    f_ptr ptr[] = {f1, f2, f3};

    int c = 0;
    while (c < 3)
    {   
        ptr[c](c);
        ++c;
    }

    return 0;
}

typedef void (*f_ptr)(int);typedef void (*f_ptr)(); 都在我的程序中工作。

它们是不同的。

typedef void (*f_ptr)(int) 声明了一个函数指针,它只接受一个 int 参数,returns 什么都不接受。

而对于 typedef void (*f_ptr)(),函数指针采用未指定数量的参数,并且 returns 什么都没有。

According to the SEI CERT C Coding Standard,建议在函数不接受参数时显式指定void

根据我的一点汇编经验:当你用一个参数调用一个函数时,它会将参数压入堆栈,然后执行该函数。然后函数从栈顶读取参数。

如果你调用 f_ptr 时不带任何参数,你不会得到错误,你只会在 var 中得到一个垃圾值。如果你用 100 个参数调用它,你只会得到第一个。

我认为编译器不阻止你的唯一原因是它不够聪明。