typedef with functions

Jan 9, 2013 at 12:23am
How would I define a function declared using typedef?

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main (int argc, char * argv)
{

  typedef int multiply(int arg1, int arg2);
  multiply mult_function_1;

  return 0;

}


I.e., provide the function body to mult_function_1; this does not work:

1
2
3
4
5
6
7
8

  multiply mult_function_1
  {
    int product = arg1 * arg2;
    return (product);
  }


Last edited on Jan 9, 2013 at 12:25am
Jan 9, 2013 at 12:57am
According to the C++ Standard
A typedef of function type may be used to declare a function but shall not be used to define a function


So your code should look like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>

int main (int argc, char * argv)
{

  typedef int multiply(int arg1, int arg2);
  multiply mult_function_1;

  printf( "%d\n", mult_function_1( 2, 3 ) );

  return 0;
}

int mult_function_1( int x, int y )
{
   // for example
   return ( x * y );
}
Last edited on Jan 9, 2013 at 1:07am
Jan 9, 2013 at 1:55am
Thanks, but then typedef functions appear to be completely pointless. When
would one use them instead of typedef pointer functions?
Jan 9, 2013 at 6:48am
typedef is useful for simple variable naming. It's also useful for renaming iterators. I can't recommend using it for functions/methods. That is just making whoever is reading the code more confused.
Last edited on Jan 9, 2013 at 6:51am
Jan 9, 2013 at 6:55am
You can typedef a function pointer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <cstdio>

int mult_function_1( int x, int y );

typedef int (*func)(int, int); // func is a function pointer to a function that accepts two ints and returns an int

int main (int argc, char * argv)
{
  func multiply = mult_function_1;

  printf( "%d\n", multiply( 2, 3 ) );

  return 0;
}

int mult_function_1( int x, int y )
{
   // for example
   return ( x * y );
}
Last edited on Jan 9, 2013 at 6:58am
Topic archived. No new replies allowed.