0

I apologize if this was asked many times. I'm trying to understand why both of this works fine without any warnings or other visible issues (in Xcode):

int testFunctionAcceptingIntPointer(int * p) {         
    return *p = *p +5;
}

void test() {
    int testY = 7;
    typedef int (*MyPointerToFunction)(int*);
    // Both this (simply a function name):
    MyPointerToFunction functionPointer = testFunctionAcceptingIntPointer;
    // And this works (pointer to function):
    MyPointerToFunction functionPointer = &testFunctionAcceptingIntPointer;
    int y = functionPointer(&testY);
}
3
  • You define functionPointer twice in your test() you should receive an error for that. Commented Dec 18, 2012 at 15:55
  • no no ANY of this. One of it is commented when testing Commented Dec 18, 2012 at 15:55
  • 1
    MyPointerToFunction functionPointer = testFunctionAcceptingIntPointer; is syntactic sugar of the other version. Commented Dec 18, 2012 at 15:57

1 Answer 1

5

The code works fine without warnings both ways because a function designator is converted to a function pointer

MyPointerToFunction functionPointer = testFunctionAcceptingIntPointer;

unless it is the operand of the address operator

MyPointerToFunction functionPointer = &testFunctionAcceptingIntPointer;

(or sizeof and _Alignof).

In the first assignment, you don't use &, so the automatic conversion is done, resulting in a function pointer of appropriate type, in the second, you explicitly take the address, resulting in a function pointer of the appropriate type.

Sign up to request clarification or add additional context in comments.

1 Comment

The fun thing about the automatic conversion to a pointer is that you could also call int y = ************functionPointer(&testY); if you like asterisks. After each dereference, it's converted to a pointer again ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.