adambard / adambard/learnxinyminutes-docs

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

Đang mở
#2,850 2 bình luận 0 reaction 0 người được giao Xem trên GitHub
Ngôn ngữ chính
Markdown
Star
12.3k
Fork
3.7k
Merge trung bình
13 giờ 10 phút
Pull request đã merge (30 ngày)
6

Mô tả

```
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).

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.