C Programming · Interview question

How do you declare a pointer to a function, and why is typedef recommended?

A strong answer

The syntax is return_type (*name)(parameter_types), for example int (*op)(int, int) is a pointer to a function taking two ints and returning int. The parentheses around *name are essential: without them, int *op(int, int) declares a function that returns int *, which is a completely different thing. The syntax gets worse fast for functions returning pointers or taking function-pointer parameters, so the idiom is to typedef it: typedef int (*BinaryOp)(int, int); then you write BinaryOp op = add;, which reads naturally and makes function-pointer parameters and arrays legible. Assigning needs no & (the function name decays to its address) and calling needs no * (op(3,4) works), though both decorated forms are also legal.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Function Pointers & Callbacks

Store a function in a variable, pass behavior as an argument, and build dispatch tables: the mechanism behind qsort, HAL callbacks, and interrupt vector tables.

More Function Pointers & Callbacks questions

Browse all 472 interview questions