I came across a strange function pointer,
void * (*f1(void(*f2)(void)))(int ) ;
What does the f1 represent here ?
T (*f(U))(V)
declares f as a function which takes a U and returns a pointer to a function from V to T (i.e. a T (*)(V)).
So f1 is a function that takes a void (*)(void) and returns a void* (*)(int).
Naming the types makes it more readable:
typedef void (*parameter)();
typedef void* (*result)(int);
result f1(parameter f2);
(The name "f2" serves no purpose except for helping the human reading the code interpret it.)
Related
#include <iostream>
void PrintTheValue(int(*func)(int a));
int main(int argc, char **argv) {
PrintTheValue([](int a) {return a; });
return 0;
}
void PrintTheValue(int(*func)(int a)) {
std::cout << *func << std::endl;
}
In my concept of understanding the func, it would be a pointer to an int passed by value. But in this case I'm passing a lambda which doesn't seem to be called anywhere. (So there isn't any value at all?)
When I run this, it doesn't break the program, but instead printed 00EE6F80.
What does this address mean? I have no idea how to interpret it.
In my concept of understanding the func, it would be a pointer to an int passed by value.
func is a pointer to function, which takes an int and returns int.
But in this case I'm passing a lambda which doesn't seem to be called anywhere.
You're passing a lambda without capturing, which could convert to pointer to function implicitly. In PrintTheValue, *func, i.e dereference on the pointer results in a reference to function, and for being passed to operator<< of std::cout, it converts to function pointer again, then converts to bool with value true (as a non-null pointer), then you should get the result 1 (or true with the usage of std::boolalpha). If you want to call on func you could func(42) (or (*func)(42)).
A lambda is an unnamed function object of the closure type.
The crucial part for this case, this class does not overload the operator<<.
When you dereference the passed lambda in *func, there is no overload for operator<<, so it converts to nearest acceptable result which is bool (at first it reverts to a regular pointer).
The documentation:
Dereferencing a function pointer yields the lvalue identifying the pointed-to function
int f();
int (*p)() = f; // pointer p is pointing to f
(*p)(); // function f invoked through the function lvalue
// But no sense in *p
It should print 1 (since non-null pointer), which it does for me (g++). The language does allow us to do so, but there's no sense in dereferencing a pointer to function without calling the function. All the peculiarities of the function pointers are due to that they have one reasonable usage, so anything you do with them will support that usage - #Pete Becker
For more on Function Pointers check here, it will aid.
How the above declaration of function pointers work in C/C++. I first encountered this declaration while making use of the signal.h file in c programming.
This is a function pointer decalaration
void (*var_name)(int)
In this example, var_name is a pointer to a function taking one argument, integer, and that returns void. It's as if you're declaring a function called "*var_name", which takes an int and returns void; now, if *var_name is a function, then var_name must be a pointer to a function
http://cyan-lang.org/jose/courses/06-2/lc/Ponteiros-para-Funcoes.htm
It's in Portuguese, Example:
in C, we can declare a pointer to function with the syntax
void (* f) ();
In this case, f is a pointer to a function with no parameters and that returns void. F can point to a compatible function:
F = maximum;
Maximum is a function declared as
void max () {
Puts ("Hi, I'm the max");
}
Maximum can be called from f using any of the syntax below.
(* F) (); / * Maximum call * /
F (); / * Maximum call * /
I am so confused with this code in the book :
typedef int (*healthCalcFunc) (const GameCharacter&)
and I understand that
typedef double* PDouble, means the word PDouble can be used to declare a pointer to double.
But I can't figure out the meaning of typedef int (*healthCalcFunc) (const GameCharacter&)
Is there anyone can help me to explain this?
Thanks in advance
:)
typedef int (*healthCalcFunc) (const GameCharacter&);
It introduces a name called healthCalcFunc for a type which describes a function-pointer, taking one parameter of type const GameCharacter& and returning an int.
So this means, if you've a function as:
int some_function(const GameCharacter&)
{
//...
}
Then you can create a pointer-object which would point to the above function as:
healthCalcFunc pfun = some_function;
and then use pfun in place of some_function as:
some_function(args); /normal call
pfun(args); //calling using function pointer
//it is exactly same as the previous call
And benefit with this approach is that you can pass around pfun (or some_function) to other function as:
void other_function(healthCalcFunc pfun)
{
//..
pfun(args); //invoke the function!
//..
}
healthCalcFunc pfun = some_function;
other_function(some_function);
other_function(pfun);
Here other_function will use the function pointer to invoke the function. That way, next time you can pass another function matching the function signature to other_function and other_function will invoke that another function instead.
In cases like this, operator precedence tends to get in the way.
What this creates is an alias (named healthCalcFunc) for the type "pointer to a function taking a reference to a const GameCharacter as its parameter and returning an int".
int: return type
(*healthCalcFunc): Pointer to function -- must be in parens to bind the * to the name instead of the preceding int, which would declare a function returning a pointer instead of the desired pointer to a function.
(const GameCharacter &): the parameter list for the type of function this will point at.
It's a function pointer - hopefully your book will have explained these somewhere; if not, your favourite search engine should be able to point you in the right direction.
That is typedef for a function pointer for functions which return int and take const GameCharacter& as an argument.
You can create a function pointer using healthCalcFunc hp = &MyFunc; then use it as int n = (*hp)(GameCharacter());. Here MyFunc will have this signature: int MyFunc(const GameCharecter&);.
This is a function type definition. At first glance, it's strange, but you'll get used to it. basically, what it says is, define a type named healthCalcFunc, whose return value is an integer, and takes a constant GameCharacter reference as its only argument.
In general, the form of a function pointer declaration is as follows:
typedef return_type (*new_function_typename)(typeof_arg1, typeof_arg2, ...);
And you can use it like this:
new_function_typename functor;
functor = some_other_functions_name;
// or
functor = dlsym(dlopen_handle, "some_function_name"); // for dynamic loading
int retval = functor(arg1, arg2);
I'm reading some material about function pointer in C++, and come across one function definition which I do not understand.
Standard function definition have the form:
type name (param...)
But the following definition seems a little strange to me. Can anyone explain it to me ?
Thanks.
float (*GetPtr1(const char opCode)) (float, float)<br>
{
if(opCode == '+')
return &Plus;
else
return &Minus; // default if invalid operator was passed
}
Note: Plus and Minus are two functions with param (float, float) and return a float.
GetPtr1 is a function that takes an opcode char and returns a pointer to a function. The function it returns takes two floats and returns a float.
A lot of times it's easier to read if you do something like this:
typedef float (*FloatOperationFuncPtr) (float, float);
FloatOperationFuncPtr GetPtr1(const char opCode)
{
if(opCode == '+')
return &Plus;
else
return &Minus; // default if invalid operator was passed
}
The rule for reading hairy declarations is to start with the leftmost identifier and work your way out, remembering that () and [] bind before * (i.e., *a[] is an array of pointers, (*a)[] is a pointer to an array, *f() is a function returning a pointer, and (*f)() is a pointer to a function):
GetPtr1 -- GetPtr1
GetPtr1( ) -- is a function
GetPtr1( opCode) -- taking a single parameter named opCode
GetPtr1(const char opCode) -- of type const char
*GetPtr1(const char opCode) -- and returning a pointer
(*GetPtr1(const char opCode)) ( ) -- to a function
(*GetPtr1(const char opCode)) (float, float) -- taking two parameters of type float
float (*GetPtr1(const char opCode)) (float, float) -- and returning float
So, if opCode is equal to '+', GetPtr1 will return a pointer to the function Plus, and if it's '-', it will return a pointer to the function Minus.
C and C++ declaration syntax is expression-centric (much as Bjarne would like to pretend otherwise); the form of the declaration should match the form of the expression as it would be used in the code.
If we have a function f that returns a pointer to int and we want to access the value being pointed to, we execute the function and dereference the result:
x = *f();
The type of the expression *f() is int, so the declaration/definition for the function is
int *f() { ... }
Now suppose we have a function f1 that returns a pointer to the function f defined above, and we want to access that integer value by calling f1. We need to call f1, derefence the result (which is the function f), and execute it, and then dereference that result (since f returns a pointer):
x = *(*f1())(); // *f1() == f, so (*f1())() == f() and *(*f1())() == *f()
The type of the expression *(*f1())() is int, so the decaration/definition for f1 needs to be
int *(*f1())() { return f; }
Always nice to know about http://cdecl.org for such situations. Be aware that it only works if you remove the parameter names. This is what you get for float(*GetPtr1(const char ))(float, float):
declare GetPtr1 as function (const char) returning pointer to function (float, float) returning float
It's a function that takes a const char and returns a pointer to a function that takes float, float and returns a float.
That means a function which takes a character and returns a pointer to a function that takes two floats and returns a float.
GetPtr1 is a function that takes two float as input parameters and returns a pointer to a function. This is much more clear:
typedef float(*Func)(float, float);
Func GetPtr1(const char opCode)
{
if(opCode == '+')
return &Plus;
else
return &Minus; // default if invalid operator was passed
}
What is this syntax for in C++? Can someone point me to the technical term so I can see if I find anything in my text?
At first I thought it was a prototype but then the = and (*fn) threw me off...
Here is my example:
void (*fn) (int&,int&) = x;
It can be rewritten to
typedef void (*T) (int&, int&);
T fn = x;
The 2nd statement is obvious, which should have solved that = x; question. In the 1st statement, we make T as a synonym as the type void(*)(int&, int&), which means:
a pointer to a function ((*…))
returning void
and taking 2 arguments: int&, int&.
That is a function pointer to a function taking two int reference parameters, which returns nothing. The function pointer is called fn and is being assigned the value in x.
This declares and initializes a function pointer.
The name of the variable is fn, and it points to a function with the following signature:
void pointedToFunction(int&, int&)
The variable fn is initialized to the value contained in x.
The pointed-to function can be called using the following syntax:
int a;
int b;
(*fn)(a,b);
This is equivalent to
int a;
int b;
pointedToFunction(a,b);
Function pointer.
http://www.newty.de/fpt/intro.html#what
^ Okay source for a beginner. :-)
This is a pointer to a function that takes two references to ints and returns void.
That seems like a function pointer to a method that takes two integer references and does not return anything. The pointer will be named fn. You are assigning it to the address of x, which is hopefully a function that matches this description.
It's a function pointer to a function that takes 2 integers as arguments and returns void. x must be a function name.
It's a function pointer variable that gets initialized to the stuff to the right of =.
The function type could be written like this:
typedef void func_t(int&,int&);
The function pointer than would be:
typedef func_t *fn_t;
With these definitions the variable declaration would be much clearer:
fn_t fn = ...;
Wikipedia page with a few links on the subject: http://en.wikipedia.org/wiki/Function_pointer