Function call syntax through a pointer dereference - c++

Consider the code
int add(int a, int b)
{
return a + b;
}
int main()
{
std::cout << (*add)(3, 2);
}
What is the point of dereferencing the function pointer ???
I can't think of such a use case where it would give an advantage ...
Why this function call syntax exists in C++ ?

This syntax exists because C had it, and C++ syntax was originally based on C.
There is no difference in the code behaviour of f(args) and (*f)(args).

I can't be sure if I am right, but here is a possible explanation:
Every function in c and as well as in c++ is a potential variable.
Possible declaration of function is:
int (*MyFunction)(int, double);
In this case- Variable name: MyFunction | Type: function that returns int with int, double parameters.
So, even when you declare function, you actually declare variable with a "function" type. In this case, it is make sense why can you use, in your case (*add)(3, 2) for function calling (or using a variable).
It may by more clearly for you to have a look on lambda expressions, which can make a function implementation, and then let you use it like a local function variable:
int(*MyFunction)(int, double) = [](int a, double b) -> int {
return (int)((a + b) * 10);
};
Here we declare on function type variable, and implement a function for it with a lambda expression. Now we can use it in two forms:
MyFunction(1, 2.5); // Like a regular function
(*MyFunction)(1, 2.5); // As a function type variable
Again, it is the most sense explanation that I could think of. I don't sure if it is a right/best/fully explanation, but I hope it gave you a new perspective of functions.

Related

Function pointer syntax query [duplicate]

Normally, when declaring some variable, you put its type before it, like:
int a;
a function pointer may have type like: int(*)(int,int), in case we point to a function that takes two integers and returns an integer. But, when declaring such a pointer, its identifier is not after the type, like:
int(*)(int,int) mypointer;
instead, you must write the identifier in the middle:
int(*mypointer)(int,int);
why is this so?
I explain this in my answer to Why was the C syntax for arrays, pointers, and functions designed this way?, and it basically comes down to:
the language authors preferred to make the syntax variable-centric rather than type-centric. That is, they wanted a programmer to look at the declaration and think "if I write the expression *func(arg), that'll result in an int; if I write *arg[N] I'll have a float" rather than "func must be a pointer to a function taking this and returning that".
The C entry on Wikipedia claims that:
Ritchie's idea was to declare identifiers in contexts resembling their use: "declaration reflects use".
...citing p122 of K&R2.
This structure reflects how a normal function is declared (and used).
Consider a normal function definition:
int foo (int bar, int baz, int quux);
Now consider defining a function pointer to a function of the same signature:
int (*foo) (int, int, int);
Notice how the two structures mirror each other? That makes *foo much easier to identify as a function pointer rather than as something else.
If you're dealing with a function (not a pointer to one), the name is in the middle too. It goes like: return-type function-name "(" argument-list ")" .... For example, in int foo(int), int is the return type, foo the name and int the argument list.
A pointer to a function works pretty much the same way -- return type, then name, then argument list. In this case, we have to add a * to make it a pointer, and (since the * for a pointer is prefix) a pair of parentheses to bind the * to the name instead of the return type. For example, int *foo(int) would mean a function named foo that takes an int parameter and returns a pointer to an int. To get the * bound to foo instead, we need parentheses, giving int (*foo)(int).
This gets particularly ugly when you need an array of pointers to functions. In such a case, most people find it easiest to use a typedef for the pointer type, then create an array of that type:
typedef int (*fptr)(int);
fptr array[10];
I had seen at some places function pointers declared as
int (*foo) (int a, int b);
and at some places a and b are not mentioned and both still works.
so
int (*foo) (int, int)
is also correct.
A very simple way that I found to remember is as mentioned below:
Suppose function is declared as:
int function (int a , int b);
Step1: Simply put function in parentheses:
int (function) (int a , int b);
Step2: Place a * in front of function name and change the name:
int (*funcPntr) (int a , int b);
PS: I am not following proper coding guidelines for naming convention etc. in this answer.

why is function pointer definition different from normal pointer? [duplicate]

Normally, when declaring some variable, you put its type before it, like:
int a;
a function pointer may have type like: int(*)(int,int), in case we point to a function that takes two integers and returns an integer. But, when declaring such a pointer, its identifier is not after the type, like:
int(*)(int,int) mypointer;
instead, you must write the identifier in the middle:
int(*mypointer)(int,int);
why is this so?
I explain this in my answer to Why was the C syntax for arrays, pointers, and functions designed this way?, and it basically comes down to:
the language authors preferred to make the syntax variable-centric rather than type-centric. That is, they wanted a programmer to look at the declaration and think "if I write the expression *func(arg), that'll result in an int; if I write *arg[N] I'll have a float" rather than "func must be a pointer to a function taking this and returning that".
The C entry on Wikipedia claims that:
Ritchie's idea was to declare identifiers in contexts resembling their use: "declaration reflects use".
...citing p122 of K&R2.
This structure reflects how a normal function is declared (and used).
Consider a normal function definition:
int foo (int bar, int baz, int quux);
Now consider defining a function pointer to a function of the same signature:
int (*foo) (int, int, int);
Notice how the two structures mirror each other? That makes *foo much easier to identify as a function pointer rather than as something else.
If you're dealing with a function (not a pointer to one), the name is in the middle too. It goes like: return-type function-name "(" argument-list ")" .... For example, in int foo(int), int is the return type, foo the name and int the argument list.
A pointer to a function works pretty much the same way -- return type, then name, then argument list. In this case, we have to add a * to make it a pointer, and (since the * for a pointer is prefix) a pair of parentheses to bind the * to the name instead of the return type. For example, int *foo(int) would mean a function named foo that takes an int parameter and returns a pointer to an int. To get the * bound to foo instead, we need parentheses, giving int (*foo)(int).
This gets particularly ugly when you need an array of pointers to functions. In such a case, most people find it easiest to use a typedef for the pointer type, then create an array of that type:
typedef int (*fptr)(int);
fptr array[10];
I had seen at some places function pointers declared as
int (*foo) (int a, int b);
and at some places a and b are not mentioned and both still works.
so
int (*foo) (int, int)
is also correct.
A very simple way that I found to remember is as mentioned below:
Suppose function is declared as:
int function (int a , int b);
Step1: Simply put function in parentheses:
int (function) (int a , int b);
Step2: Place a * in front of function name and change the name:
int (*funcPntr) (int a , int b);
PS: I am not following proper coding guidelines for naming convention etc. in this answer.

About to pass a reference as an argument in a function to alter the value of the argument variable.

I was reading "Beginning C++ Through Game Programming, Fourth Edition" when I found a section about to pass a reference as an argument in a function that says:
"Pass a reference only when you want to alter the value
of the argument variable. However, you should try to avoid changing
argument variables whenever possible."
Basically it says that I shoud avoid to do something like this:
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
But, why should I avoid doing this?
I found very useful to create functions to change variables, because these functions keep my code organized avoiding me to write every variable change in the main() function, and they also avoid me to write the same code repeatedly.
What alternative is there if I should not do this?
With the case of swap, pass by reference shoud be used, because multiple variables are being changed in the function and the expected behavior of the function is obvious. If you were only changing one variable or have a function that should be returning a result, then it is better to return a value for the most part (With some exceptions). For example, supoose you had a function sum():
int sum(int a, int b)
{
return a + b;
}
Usage of this function might be:
int x = sum(1, 2); // Obvious and to the point
Since there is no need to change any of the variables, one would use pass by value here (Pass by const reference doesn't matter here, since POD types are pretty small). If you used pass by reference here, then the function would have changed to:
void sum(int a, int b, int& sum)
{
sum = a + b;
}
Usage of the function above might be:
int s;
sum(1, 2, s); // Obscure, unclear
Disadvantages of this are that it is unclear what the intent of the function is, and now the result of the function cannot be passed to another function in one line. So pass by reference should only be used when absolutely necessary.
On a side note, using a const reference for passing large objects to functions is always recommended, since it avoids a copy.

Does 'void (*)(int)' the same with 'void (^)(int)'?

Today, I'm working on a callback pass from C++ to Objective-c method.
Finally, I worked it out, but a few code confuse me.
In Objective-c, people ordinary use block to implement a callback, a block declare looks like this:
returnType (^blockName)(parameterTypes)
I also learned about C++ callback, a same type callback defined like this:
returnType (*funcName)(parameterTypes)
When I passed a callback from C++ to Objective-c, compiler warning me:
"Cannot initialize a parameter of type 'void (^)(int)' with an rvalue of type 'void (*)(int)"
Finally, I changed ^ to *, it works. I wondering to know, what's the difference between ^ and * in definition, is that have the same behavior?
This is a block:
returnType (^blockName)(parameterTypes)
This is a function pointer:
returnType (*funcName)(parameterTypes)
They aren't compatible.
Standard C and C++ do not have callable blocks. Apparently, however, some compilers for those languages do implement the feature as an extension. Some of the docs I see suggest that it's an Apple extension to Objective C, too, but inasmuch as Objective C is little used outside the Apple world, that may be a distinction without a difference.
In whatever language, if you implement a callback as a function, then you must present that callback to the intended caller via a function pointer, and the caller must be prepared to accept it in that form. On the other hand, if you implement a callback as a block then you must present it to the caller via a block pointer, and the caller must be prepared to accept that form. The two are not interchangeable, and they have different syntaxes, which you have presented. It would be possible to design a mechanism that could accept both forms, however, via separate parameters or altogether separate registration functions.
Objective-C blocks (^) are incompatible with function pointers (*).
Compared to function pointers, they have the benefit of being able to capture values and variables from the surrounding context (they are closures).
It's easy enough to write a wrapper that calls a function pointer from a block:
typedef int (*funptr)(int);
typedef int (^funblock)(int);
int use_block_callback(int y, funblock fb)
{
return fb(y);
}
int use_funptr_callback(int y, funptr f)
{
return use_block_callback(y, ^ int (int x) { return f(x); });
}
int add_one(int x) { return x + 1; }
int foo(int x)
{
return use_funptr_callback(23, add_one);
}
// Or
int (*some_pointer)(int) = add_one;
int (^some_block)(int) = ^ int (int x) { return some_pointer(x); }
("Programming with Objective-C" about blocks.)

How can I define a function pointer that takes the same arguments and return value as a given function?

For example, I have a function foo:
int foo(int a, int b)
{
return a + b;
}
I can define a function pointer:
int (*pfoo)(int, int);
But how can I do this dynamically in program?
I want a function that takes a function as a parameter, and return a function pointer that takes the same arguments and return value as a given function.
Then I can use it like this:
void* pfoo = getFuncPtrFromFunc(foo);
Which does what the code above did.
Is this possible?
You cannot do this at run-time (i.e. dynamically); remember that all types (and function pointers are types) are statically determined at compile-time.
Imagine if you could do this, and you somehow obtained a function-pointer whose type was variable (i.e. it could point to a float (*)(int,int) or a char (*)(float)). How would you ever be able to call that and provide a meaningful list of arguments?
You can, however, get this information at compile-time; one way is to use the Boost TypeTraits library.
c++ is a static typed language, and doesn't allow to do what you want.