簡體   English   中英

從另一個函數返回一個函數指針

[英]Returning a function pointer from another function

我正在嘗試編寫一個函數,該函數然后將通過要運行的測試:

static uint8_t (*GetTest(uint8_t test_type))(void)
{
   switch(test_type) {
      case 0:
          return &test_a;

      case 1:
          return etc etc...
   }
}

static void test_a(void)
{
   ;
}

但是,我從編譯器收到警告,說返回值類型與函數類型不匹配。 我相信這是由於該函數的靜態聲明引起的,但是我不確定如何包括它們。

您需要確定函數的返回類型。

您想要這個:

#include <stdint.h>

static uint8_t test_a(void)
{
  return 1;  // you need to return something
}

static uint8_t(*GetTest(uint8_t test_type))(void)
{
  switch (test_type) {
  case 0:
    return &test_a;

//  case 1:
   // return etc etc...
  }
}

或這個:

#include <stdint.h>

static void test_a(void)
{

}

static void(*GetTest(uint8_t test_type))(void)
{
  switch (test_type) {
  case 0:
    return &test_a;

//  case 1:
   // return etc etc...
  }
}

上面的兩個版本都編譯時沒有警告。

要添加到@Jabberwocky的答案中,創建typedef可能會更簡單,即:

// this is a function with no parameters and no return value
typedef void(*TestFn)(void);

這樣可以更輕松地查看GetTest函數返回的內容以及它作為參數接受的內容:

// this is a function which accepts one uint8_t parameter,
// and returns a function with `TestFn` signature
static TestFn GetTest(uint8_t test_type)
{
    switch (test_type)
    {
        case 0: return &test_a;
        case 1: ...
    }
}

看來您正在尋找這樣的東西:

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

typedef int (*fx_p)(int, int);

int testadd(int a, int b) { return a+b; }
int testsub(int a, int b) { return a-b; }
int testmul(int a, int b) { return a*b; }
int testdiv(int a, int b) { return a/b; }

fx_p getfx(int n) {
    switch (n) {
        default: return testadd;
        case 4: case 5: case 6: return testsub;
        case 7: case 8: return testmul;
        case 9: return testdiv;
    }
}

int main(void) {
    // missing srand on purpose
    for (int k = 0; k < 20; k++) printf("%d\n", getfx(rand() % 10)(42, 10));
    return 0;
}

您可以看到它在ideone上運行: https ://ideone.com/U3it8W

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM