Typedef with Function Pointer in C
Level 5280 keystrokes
Uses typedef to name the function pointer type Operation, stores add and multiply in an array of that type and calls each one through the array with 3 and 4. It prints Add(3, 4) = 7 and Multiply(3, 4) = 12.
C code
// Operation now names the type "pointer to a function taking two ints and returning int"1typedef int (*Operation)(int, int);2 // Matches the Operation signature; returns a + b3int add(int a, int b) { return a + b; }// Same signature; returns a * b4int multiply(int a, int b) { return a * b; }5 // The typedef keeps this array of function pointers readable6Operation ops[2] = {add, multiply};// Display names in the same order as ops7char *names[2] = {"Add", "Multiply"};8 // Visits both functions9for (int i = 0; i < 2; i++) { // ops[i](3, 4) calls the i-th function: Add(3, 4) = 7, then Multiply(3, 4) = 1210 printf("%s(3, 4) = %d\n", names[i], ops[i](3, 4));11}Output
Add(3, 4) = 7 Multiply(3, 4) = 12
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C code and how often they appear.
,× 9;× 8(× 8)× 8"× 6{× 5}× 5[× 4]× 4=× 4