0

I am not sure whether the following is possible. Can someone give an equivalent for this requirement?

if(dimension==2)
  function = function2D();
else if(dimension==3)
  function = function3D();

for(....) {
  function();
}
SKPS
  • 5,433
  • 5
  • 29
  • 63

4 Answers4

5

It is possible, assuming two things:

  1. Both function2D() and function3D() have the same signature and return type.
  2. function is a function pointer, with the same return type and parameters as both function2D and function3D.

The technique you are exploring is very similar to the one used in constructing a jump table. You have a function pointer, which you assign (and call through) at run-time based on run-time conditions.

Here is an example:

int function2D()
{
  // ...
}

int function3D()
{ 
  // ...
}

int main()
{
  int (*function)();  // Declaration of a pointer named 'function', which is a function pointer.  The pointer points to a function returning an 'int' and takes no parameters.

  // ...
  if(dimension==2)
    function = function2D;  // note no parens here.  We want the address of the function -- not to call the function
  else if(dimension==3)
    function = function3D;

  for (...)
  {
    function();
  }
}
Community
  • 1
  • 1
John Dibling
  • 99,718
  • 31
  • 186
  • 324
4

You can use function pointers.

There's a tutorial here but basically what you do is declare it like this:

void (*foo)(int);

where the function has one integer argument.

Then you call it like this:

void my_int_func(int x)
{
    printf( "%d\n", x );
}


int main()
{
    void (*foo)(int);
    foo = &my_int_func;

    /* call my_int_func (note that you do not need to write (*foo)(2) ) */
    foo( 2 );
    /* but if you want to, you may */
    (*foo)( 2 );

    return 0;
}

So as long as your functions have the same number and type of argument you should be able to do what you want.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
2

Since this is also tagged C++, you can use std::function if you have access to C++11, or std::tr1::function if your compiler supports C++98/03 and TR1.

int function2d();
int function3D(); 

int main() {
    std::function<int (void)> f; // replace this with the signature you require.
    if (dimension == 2)
        f = function2D;
    else if (dimension == 3)
        f = function3D;
    int result = f(); // Call the function.
}

As mentioned in the other answers, make sure your functions have the same signature and all will be well.

If your compiler doesn't offer std::function or std::tr1::function, there's always the boost library.

bstamour
  • 7,746
  • 1
  • 26
  • 39
1

Since you choose C++

Here's with std::function example in C++11

#include <functional>
#include <iostream>

int function2D( void )
{
  // ...
}

int function3D( void ) 
{ 
  // ...
}

int main()
{

    std::function<int(void)> fun = function2D;

    fun();

}
P0W
  • 46,614
  • 9
  • 72
  • 119