RustyHearth
RustyHearth

Reputation: 344

A pointer to function in c++

When I did something with pointer to function I noticed something and didn't understand

I did this:

#include <stdio.h>

int callback(void)
{
   return 5;
}

void call(int (*cpmpare)(void))
{
    int x;
    x = cpmpare();
    printf("%d", x);
}

void main()
{
    int (*compare)(void);
    int *a, b;
    b = 5;
    a = &b;
    compare = callback;
    printf("%p\n", &callback);
    printf("%p\n", compare);
    call(&callback);
}

And I did compare = &callback instead compare = callback and it did the same, compare got the same address as did callback.

Why did it work both ways?

From what I know comparing a pointer and a regular variable will be wrong.

Upvotes: 3

Views: 124

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490138

The C committee decided that (since the meaning was unambiguous) that the name of a function (not followed by parens to call the function) would evaluate to the address of the function (in much the same way that the name of an array evaluates to the address of the beginning of the array).

The official wording is (§C99, 6.3.2.1/4):

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator or the unary & operator, a function designator with type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to function returning type’’.

Although I'm not sure Bjarne or the C++ committee was nearly so excited about the idea, they apparently decided to go along with this, so the same remains true in C++. The (primary) reason I think they were unenthused about this is that although they could have done the same with the name of a member function that wasn't followed by parens to call that member function, they chose not to -- to get a pointer to a member function, you must use the address-of operator (&).

Upvotes: 4

Carl Norum
Carl Norum

Reputation: 224944

Functions, like arrays, decay into pointers in some contexts. It's almost always the same to use &function or function. In your example that's definitely the case. These two statements are semantically identical:

compare = callback;
compare = &callback;

As are these two:

call(&callback);
call(callback);

Likewise, when you want to use the function pointer, the * is also optional:

x = cpmpare();
x = (*cpmpare)();

Upvotes: 6

Related Questions