首页 > 解决方案 > 在 C 语言中使用数组声明类似的函数

问题描述

如何使用数组来声明类似的函数?我想节省一些空间。下面是一个例子:

void checkEntered1(int button){
  if (entered[0] != 0){
    checkEntered2(button); 
  }
}

void checkEntered2(int button){
  if (entered[1] != 0){
    checkEntered3(button);
  }
}

void checkEntered3(int button){
  if (entered[2] != 0){
    checkEntered4(button);
  }
}

void checkEntered4(int button){
  if (entered[3] != 0){
    checkEntered5(button);
  }
}

下面的工作吗?这是一个有效的声明吗?


for (int i=1; i<=4; i++){
  void checkEntered[i](int button){
    if (entered[i-1] != 0){
      checkEntered[i+1](button); 
    }
  }
}

标签: arrayscfunctionarduinodeclaration

解决方案


我猜你需要一个函数指针数组。


void dispatch_button(int button) {
  typedef void button_handler_t(int);
  static button_handler_t* handlers[] = { checkEntered1, checkEntered2, ... };
  size_t n_handlers = sizeof handlers / sizeof handlers[0];

  for (size_t i = 0; i < n_handlers; ++i)
    if (entered[i] == 0) {
      handlers[i](button);
      return;
    }
  // error when no handler was found
}

推荐阅读