Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pointer to functions, Beginner Question

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

like image 294
BobAlmond Avatar asked Apr 06 '10 17:04

BobAlmond


People also ask

How do you use a pointer to a function in C?

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.

Can we use pointer with function in C?

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.

How do you call a function with a 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.

Which of the following is a pointer pointing to function?

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.


1 Answers

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 &.

like image 104
Kirill V. Lyadvinsky Avatar answered Oct 14 '22 00:10

Kirill V. Lyadvinsky