typedef with functions

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
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
Thanks, but then typedef functions appear to be completely pointless. When
would one use them instead of typedef pointer functions?
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
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
Topic archived. No new replies allowed.