I want to ask about pointer in C++
I have some simple code:
int add(int a, int b){
return a+b;
}
int runner(int x,int y, int (*functocall)(int, int)){
return (*functocall)(x,y);
}
now, suppose I call those functions using this way :
cout<<runner(2,5,&add);
or maybe
cout<<runner(2,5,add);
is there any difference? because when I tried, the result is the same and with no error.
Thanks a lot
A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.
Calling a function using a pointer is similar to calling a function in the usual way using the name of the function. int length = 5; // Different ways to call the function // 1. using function name int area = areaSquare(length); // 2. using function pointer (a) int area = (*pointer)(length); // 3.
Syntax of function pointer In the above declaration, *ip is a pointer that points to a function which returns an int value and accepts an integer value as an argument.
Function will be implicitly casted to a pointer according to C++ Standard (4.3/1). There is no difference. However this conversion never applies to nonstatic member functions. For them you should explicitly write &
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With