Reputation: 44762
typedef void int_void(int);
int_void
is a function taking an integer and returning nothing.
My question is: can it be used "alone", without a pointer? That is, is it possible to use it as simply int_void
and not int_void*
?
typedef void int_void(int);
int_void test;
This code compiles. But can test
be somehow used or assigned to something (without a cast)?
/* Even this does not work (error: assignment of function) */
typedef void int_void(int);
int_void test, test2;
test = test2;
Upvotes: 4
Views: 1397
Reputation:
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)
{
}
Upvotes: 7
Reputation:
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);
}
Upvotes: 1
Reputation: 20726
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);
Upvotes: 3
Reputation: 2636
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".
Upvotes: -1
Reputation: 27365
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.
Upvotes: 2