【问题标题】:What is the meaning in C when a function is in another function's name (not in the arguments)?当一个函数在另一个函数的名称中(而不是在参数中)时,C 中的含义是什么?
【发布时间】:2020-11-25 07:14:29
【问题描述】:

为什么 “void (*parse(char *op))(int, int)” 写成这样? (主要添加以给出用例),它被一个指针“有趣”调用,带有 argv[2] 没有整数(第 18 行)......然后再次作为“有趣”使用整数(第 21 行)?

void    (*parse(char *op))(int, int)
{
    if (!strcmp(op, "+"))
        return(other stuff...); 
    else
        return (0);
}
int     main(int argc, char *argv[]){
    int a;
    int b;
    void    (*fun)(int, int);

    if (argc == 4){
        a = atoi(argv[1]);
        fun = parse(argv[2]);
        b = atoi(argv[3]);
        if (fun)
            fun(a, b);
        else
            return(0);
    }
    return(0);
}

它在技术上是如何工作的,它只是用更简单的方式来炫耀它还是这是唯一正确的语法?

【问题讨论】:

  • 欢迎享受函数指针的乐趣。 parse() 是一个返回指向函数的指针的函数。知道other stuff... 是什么会很有趣/很有帮助。

标签: c function-pointers definition


【解决方案1】:

parse() 是一个返回函数指针的函数。不过,您可以将typedef 与返回函数的类型一起使用,使其看起来更好看:

#include <string.h>
#include <stdlib.h>

// parser_func describes a function that takes two ints and returns nothing
typedef void (*parser_func)(int, int);

// Like this one.
void somefunc(int a, int b) {}

// And parse() is a function that takes a char* and returns a
// pointer to a function that matches parser_func.
parser_func parse(char *op) {
  if (!strcmp(op, "+"))
    return somefunc;
  else
    return NULL;
}

int main(int argc, char *argv[]) {
  int a;
  int b;
  parser_func fun; // Function pointer

  if (argc == 4) {
    a = atoi(argv[1]);
    fun = parse(argv[2]); // Assign a function to fun
    b = atoi(argv[3]);
    if (fun) {
      fun(a, b); // And call it if it's not null
    }
  }
  return 0;
}

【讨论】:

    【解决方案2】:

    void (*parse(char *op))(int, int)为什么会这样写?

    因为这是返回函数指针的语法。返回类型为void (*)(int, int),它是一个指向返回void 并接受两个int 参数的函数的指针。

    通常,类型别名用于使指向函数的指针更具可读性:

    typedef void operation(int, int);
    using operation = void (int, int); // equivalent C++ alternative
    
    operation* parse(char *op);
    

    【讨论】:

    • 我怀疑一个更好的 typedef 名称应该是 operator(除了这个问题也用 C++ 标记)——可能是 calculator,或者使用一些大写字母(Operator 或 @ 987654329@).
    • @JonathanLeffler 比如说operation
    猜你喜欢
    • 2019-01-20
    • 2014-10-15
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多