Function Pointer in C
Level 5258 keystrokes
Defines add, sub and mul with the same signature and a calc function that receives one of them through a function pointer and calls it. Passing each function with 10 and 5 prints 15 5 50.
C code
// Three functions share the signature int (int, int); add returns a + b1int add(int a, int b) { return a + b; }// sub returns a - b2int sub(int a, int b) { return a - b; }// mul returns a * b3int mul(int a, int b) { return a * b; }// op is a function pointer, written return_type (*name)(param_types)4int calc(int (*op)(int, int), int x, int y) { // Calls whichever function op points to and returns its result5 return op(x, y);6}// A function name used as an argument becomes its address: 10+5, 10-5, 10*5 print 15 5 507printf("%d %d %d", calc(add, 10, 5), calc(sub, 10, 5), calc(mul, 10, 5));Output
15 5 50
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.
,× 16(× 11)× 11;× 5{× 4}× 4%× 3"× 2*× 2-× 1