adambard / adambard/learnxinyminutes-docs
[c/en] Could use simpler function `typedef` syntax
- Linguagem predominante
- Markdown
- Estrelas
- 12.3k
- Forks
- 3.7k
- Merge médio
- 13h 10min
- PRs com merge (30d)
- 6
Descrição
```
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).
Guia de contribuição
Avaliação
Esta issue ainda não foi avaliada.