adambard / adambard/learnxinyminutes-docs

[c/en] Could use simpler function `typedef` syntax

未关闭
#2,850 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
主要语言
Markdown
星标
12.3k
派生
3.7k
平均合并
13 小时 10 分钟
30 天内合并 PR
6

描述

```
typedef void (*my_fnp_type)(char *);
```

This is legal, and IMHO more understandable:

```
typedef void my_fnp_type(char* meaningful_name);
```

As I'll show below, this syntax is unnecessarily hairy as well:

```
void str_reverse_through_pointer(char *str_in) {
// Define a function pointer variable, named f.
void (*f)(char *); // Signature should exactly match the target function.
f = &str_reverse; // Assign the address for the actual function (determined at run time)
// f = str_reverse; would work as well - functions decay into pointers, similar to arrays
(*f)(str_in); // Just calling the function through the pointer
// f(str_in); // That's an alternative but equally valid syntax for calling it.
}
```

I.e. the alternative syntax is less nasty. Why bother with the nasty flavor? :)

The only quirk is, when putting such a function type as a member of a `struct`, you do need to give it a `*`:

```
~ $ make test
clang -Wall -Wextra -Werror -O0 -ansi -pedantic -std=c11 test.c -o test
~ $ ./test
Hello, whirled!
~ $ cat test.c
#include

typedef void printer(const char* message);

typedef struct {
printer* function;
const char* message;
} Printer;

void print(const char* message) {
puts(message);
}

int main() {
Printer p = { .function = print, .message = "Hello, whirled!" };
p.function(p.message);
}
```

You don't need the `*` when passing such function `typedef`s to other functions. Just for `struct` members. I find this greatly improves the readability of function types, which is good, since they're so useful. The unnecessary ugliness of the classic style makes me sad. :)

Also I find the named `struct` member initializers improve readability (and I wish C++ had them).

贡献指南

打开贡献指南

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。