указатель функции typedef в C - PullRequest
0 голосов
/ 04 февраля 2020

Я просто экспериментирую с typedef для функций. Мне не ясно, почему удаление круглых скобок вокруг DISPLAY в моей функции main() приводит к тому, что этот код обрабатывает sh:

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

typedef void (*DISPLAY) (int*);

void display(int* data) {
        printf("%d\n", *data);
}

void displayThis(int *val, DISPLAY func_display) {
        func_display (val);
}

int main() {
        int x = 3;
        /*DISPLAY disp = &display;
        disp(&x);*/
        displayThis(&x, DISPLAY display);
        return 0;
}

Если я скомпилирую это и выполню, он выдаст ошибку:


bash-3.2$ gcc -g display.c
display.c:18:18: error: unexpected type name 'DISPLAY': expected expression
        displayThis(&x, DISPLAY display);
                        ^
1 error generated.
bash-3.2$ 

Вот версия с круглыми скобками DISPLAY, которая работает, как и ожидалось:

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

typedef void (*DISPLAY) (int*);

void display(int* data) {
        printf("%d\n", *data);
}

void displayThis(int *val, DISPLAY func_display) {
        func_display (val);
}

int main() {
        int x = 3;
        /*DISPLAY disp = &display;
        disp(&x);*/
        displayThis(&x, (DISPLAY) display);
        return 0;
}

Выводит, как ожидается:

bash-3.2$ gcc -g display.c
bash-3.2$ ./a.out
3

Почему круглые скобки DISPLAY имеет значение? Может кто-нибудь помочь мне лучше понять, что происходит?

Спасибо. Andy

...