2

I wrote a simple demo(test.cpp) for my question:

#include <stdio.h>
typedef void* (*SEL)(void);

int foo(int a, int b, int c) {
    return a + b + c;
}

SEL _ptr_to_foo() {
    return (SEL)foo;
}
int main() {
    SEL sel = _ptr_to_foo();

    return 0;
}

and I compiled it with g++ test.cpp -o test in my osx and compilers complained nothing.

But I'm confused about what happened here. As my opinion, SEL defines function pointer which parameter is void and returns void*. However, function foo should be a function which accepts three int parameters and returns an int as result. I think the function pointer of foo should be declared as something like int (*ptr)(int, int, int) = foo;. Why the casting in _ptr_to_foo works? What happened here?

8
  • 1
    "works" is relative. SEL is not compatible with foo(). Commented Nov 10, 2018 at 7:39
  • @Swordfish I tried to call my foo via SEL but failed because of the wrong parameter. It seems that SEL throws away my parameter information in foo. Does this mean your not compatible in your comment? Commented Nov 10, 2018 at 7:44
  • 2
    Why should the cast fail? Especially a c-style cast? Commented Nov 10, 2018 at 7:45
  • 1
    Why don't you just use the correct type? Commented Nov 10, 2018 at 7:46
  • 2
    It works because the C++ language allows it. It allows it because you may want to store a function pointer under a different type, and cast back later based on other information stored with it it. Commented Nov 10, 2018 at 7:54

2 Answers 2

3

You can store function pointers as the wrong function pointer type.

If you call them as the wrong function pointer type the behaviour of your program becomes undefined by the C++ standard.

Your use of a C-style cast becomes a reinterpret_cast<SEL>, which can do very unsafe things.

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

Comments

2

c-style casts are fairly lax in their type checking. You should use static_cast instead. This fails to compile:

return static_cast<SEL>(foo);

2 Comments

Ok, this one fails. Should I reckon this c-style cast as a bug here?
No, it is not a bug, it is by design. Using a reinterpret_cast<> in C++ will allow you to do the same ... stupid thing.

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.