You are here:

C/function pointers

Advertisement


Question
in an interview i was asked to write a program which receives 3 values and selects a function according to the value received? For eg., funcion A if 1 is received, function B for 2 and function C for 3. I was asked to do this with function pointers.
-------------------------

Followup To

Question -
What are function pointers? Why is it used? how can we use function pointer instead of switch-case?

Answer -
What are function pointers?
Function pointers are basically pointers.
Instead of holding an address of data, it holds the address of a function.

Why is it used?
To indirectly call functions.
Callbacks are implemented using this mechanism.

how can we use function pointer instead of switch-case?
No, they are not a replacement for switch-case.

Answer
int fun()
{
}

calling_fn(int ch)
{
    // Declare your function pointer here, say *fn.

    switch (ch)
    {
    case 1: fn = A;
         break;
    case 2: fn = B;
         break;
    case 3: fn = C;
         break;
    }

    fn();
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.