3 ms·
One advantage is that you can declare functions with it, which is useful when you have many different operations of the same type. For example, take a toy calcu
by evincarofautumn 10y ago
One advantage is that you can declare functions with it, which is useful when you have many different operations of the same type. For example, take a toy calculator:
typedef double binary_operation(double, double);
binary_operation add, subtract, multiply, divide;
double add(double a, double b) { return a + b; }
/* ... */
struct binary_operator {
char const *name;
binary_operation *operation;
} binary_operators[] = {
{ "+", add },
{ "-", subtract },
{ "*", multiply },
{ "/", divide },
{ NULL, NULL },
};
You can also use the function type in parameter lists, but it’s equivalent to a function pointer type.
int atexit(void function(void));
- lomnakkus 10y agoWell, yeah, obviously there's less redundancy, but I'm specifically not seeing the advantage that OP mentioned. (Which is all that I'm questioning.)
- loeg 10y agoHere's an example: typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler); Without the typedef, it's much less clear. Edit: It could instead be written as the non-pointer type: typedef void (sighandler_t)(int); And then used as: sighandler_t *signal(int signum, sighandler_t *handler); And as a function declaration: sighandler_t foo; With the pointer in the typedef, the type can't be used to declare functions.