adambard / adambard/learnxinyminutes-docs

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

オープン
#2,850 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る
主要言語
Markdown
スター
12.3k
フォーク
3.7k
平均マージ
13時間 10分
マージ済み PR(30日)
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 を短くまとめたダイジェスト。