typedef void int_void(int);
int_void
is a function taking an integer and returning nothing.
My question is: can it be
It can be used in the following cases (out of the top of my head):
generic code:
boost::function<int_void> func;
other typedefs:
typedef int_void* int_void_ptr;
declarations:
void add_callback(int_void* callback);
There may be others.
I think it's legal - the following demonstrates its use:
typedef void f(int);
void t( int a ) {
}
int main() {
f * p = t;
p(1); // call t(1)
}
and actually, this C++ code compiles (with g++) & runs - I'm really not sure how kosher it is though.
#include <stdio.h>
typedef void f(int);
void t( int a ) {
printf( "val is %d\n", a );
}
int main() {
f & p = t; // note reference not pointer
p(1);
}
What happens is that you get a shorter declaration for functions.
You can call test
, but you will need an actual test()
function.
You cannot assign anything to test because it is a label, essentially a constant value.
You can also use int_void
to define a function pointer as Neil shows.
typedef void int_void(int);
int main()
{
int_void test; /* Forward declaration of test, equivalent to:
* void test(int); */
test(5);
}
void test(int abc)
{
}
You are not declaring a variable; you are making a forward declaration of a function.
typedef void int_void(int);
int_void test;
is equivalent to
void test(int);
This should work, no casting required:
void f(int x) { printf("%d\n", x); }
int main(int argc, const char ** argv)
{
typedef void (*int_void)(int);
int_void test = f;
...
}
A function's name "devolves" into a function pointer anytime you use the function's name in something other than a function call. If is is being assigned to a func ptr of the same type, you don't need a cast.
The original
typedef int_void(int);
is not useful by itself, without using a pointer to the type. So the answer to your question is "no, you can't use that typedef without a pointer".
Pointers to functions are values in C/C++. Functions are not.