函数指针参数被忽略/不需要

S1i*_*ery 5 c function-pointers

我目前正在为微处理器编写 C 代码,我遇到了一些我无法解释的事情。我已经使用函数指针实现了命令行界面。为此,我创建了一个结构体,其中包含命令的名称、指向要运行的函数的指针以及帮助说明。

typedef void(*command)(char *);
typedef struct commandStruct {
    char const *name;
    command execute;
    char const *help;
} commandStruct;

const commandStruct commands[] =
{
    {"led", CmdLed, "Turns on or off the LED1"},
    {"AT+START_SIM", start_simulation, "Starts the simulation"},
    {"AT+STOP_SIM", stop_simulation, "Stops the simulation"},
    {"",0,""} //End of table indicator.
};

void exec_command(char *buffer)
{
    uint16 i = 0;
    char *cmd = buffer;
    char *args;
    while (buffer[i])
    {
        if(buffer[i] == '=')
        {
            buffer[i] = 0;
            args = buffer + i + 1;
            break;
        }
        i++;
    }

    uint16 cmdCount = 0;
    while(strcmp(commands[cmdCount].name,""))
    {
        if(!strcmp(commands[cmdCount].name,cmd))
        {
            commands[cmdCount].execute(args);
            break;
        }
        cmdCount++;
    }
}

void start_simulation(void) {run = 1;}
void stop_simulation(void) {run = 0;}
void CmdLed(char *args)
{
    P1DIR |= BIT0;
    if(!strcmp(args,"on")) P1OUT = 1;
    if(!strcmp(args,"off")) P1OUT = 0;
}
Run Code Online (Sandbox Code Playgroud)

exec_command我已经在上面包含了使用函数指针的函数。在底部我还放置了start_simulationstop_simulation函数以及CmdLed. 我CmdLed早些时候写过,然后回来写了start_simulationstop_simulation。我忘记了我已经将函数指针定义为以 a(char *)作为参数。然而,我惊讶地发现一切仍然编译并运行得非常好。为什么是这样?似乎任何参数都只是“转储”而不被使用。

Jab*_*cky 2

这不应该用现代编译器进行编译。

这里发生了什么:

start_simulation将使用char*参数调用,但由于start_simulation没有参数,因此参数将被简单地忽略(或在您编写时“转储”)。

请记住,在 C 函数中,参数被压入堆栈,调用者在调用后清理堆栈。因此,如果您调用一个没有参数的函数,假装它有参数,那么

  • 调用者将参数压入堆栈
  • 无参函数由调用者调用
  • 该函数忽略堆栈上的参数
  • 函数返回给调用者
  • 调用者清理堆栈

也看看这个SO问题