Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value of function in c/C++ [duplicate]

Tags:

c++

c

Possible Duplicate:
How does dereferencing of a function pointer happen?

If we have

void f() {
    printf("called");
}

Then the following code will result in output of "calledcalled":

f();
(*f)();

I don't really understand how this works…what is the difference between *f and f? And why would you call a function using the latter syntax?

like image 588
Aaron Yodaiken Avatar asked Apr 30 '11 20:04

Aaron Yodaiken


People also ask

What is function in C Plus Plus?

A function in C++ is a group of statements that together perform a specific task. Every C/C++ program has at least one function that the name is main. The main function is called by the operating system by which our code is executed.

How do you pass by reference?

Pass by reference (also called pass by address) means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function so that a copy of the address of the actual parameter is made in memory, i.e. the caller and the callee use the same variable for the parameter.

How do you write a void function in C++?

A void function with value parameters are declared by enclosing the list of types for the parameter list in the parentheses. To activate a void function with value parameters, we specify the name of the function and provide the actual arguments enclosed in parentheses.


1 Answers

There are two ways to call a function in C++:

By name:

f();

Through a function pointer:

typedef void (*fptr_t)();
fptr_t fptr = &f;
(*fptr)();

Now, using the address-of operator on a function name (&f) obviously creates a function pointer. But the function name can implicitly convert to a function pointer when certain conditions are met. So the above code could be written as:

typedef void (*fptr_t)();
fptr_t fptr = f; // no address-of operator, implicit conversion
(*fptr)();

Your second example is doing exactly this, but using a temporary variable to hold the function pointer instead of a named local variable.

I prefer to use address-of when creating function pointers, the meaning is much clearer.

A related note: The function call operator will automatically dereference a function pointer if one is provided. So this also is legal:

typedef void (*fptr_t)();
fptr_t fptr = &f;
fptr();

That's pretty useful with templates, because the same syntax works whether you have a function pointer or a functor (object implementing operator()) passed in.

And neither shortcut works with pointer-to-members, there you NEED explicit address-of and dereference operators.


In C, @Mehrdad explains that all function calls use a function pointer.

like image 157
Ben Voigt Avatar answered Oct 05 '22 23:10

Ben Voigt