Function call (NOT function pointer)

typedef void int_void(int); 

int_void is a function that takes an integer and returns nothing.

My question is: can it be used "alone" without a pointer? That is, can it be used as just 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 casting)?


 /* Even this does not work (error: assignment of function) */ typedef void int_void(int); int_void test, test2; test = test2; 
+4
source share
6 answers

What happens is that you get a shorter declaration for functions.

You can call test , but you will need the actual test() function.

You cannot assign anything for testing because it is a label, essentially a constant value.

You can also use int_void to define a function pointer, as Neil shows.


Example

 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) { } 
+7
source

You do not declare a variable; you make a direct function declaration.

 typedef void int_void(int); int_void test; 

equivalently

 void test(int); 
+3
source

It can be used in the following cases (from the head):

  • common code:

    push :: Function <int_void> FUNC;

  • other typedefs:

    typedef int_void * int_void_ptr;

  • ads:

    void add_callback (int_void * callback);

There may be others.

+2
source

I think this is 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 in fact, this C ++ code compiles (with g ++) and runs - I'm really not sure if this is kosher.

 #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); } 
+1
source

Function pointers are values ​​in C / C ++. There are no functions.

0
source

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; ... } 

The name of the function "goes" to the function pointer at any time when you use the name of the function in something other than a function call. If is is assigned to func ptr of the same type, you don't need a listing.

Original

 typedef int_void(int); 

not useful on its own without using a type pointer. Therefore, the answer to your question is β€œno, you cannot use this typedef without a pointer”.

-1
source

Source: https://habr.com/ru/post/1301837/


All Articles