c++ - Casting in function pointer assignment -


how following function pointer assignment:

exit = (void (*)()) &jump; 

different from:

exit = &jump; 

where exit function pointer defined as:

void (*exit) (); 

and 'jump' function declared as:

void jump(); 

exit = (void (*)()) &jump; 

the first 1 uses forced casting. dangerous because can screw program without letting know if types not match up, not caught @ compile time.

so if this:

int func() {return 1;} auto exit = (void (*)()) &func; 

...that bad. however, it's better if below:

exit = &jump; 

the second 1 uses compile-time type checking. safer because compiler check type at compile-time. gives stronger type guarantee.

the best option use static_cast<void(*)()> it's type-safe, , tells programmer more of intent of trying do.

auto exit = static_cast<void(*)()>(&func); 

if have c++, can try following things:

if don't want concern type, use auto.

auto exit = &func

this ensure types match up. if want examine type, use typeid().name <typeinfo> exists in c++11 , later:

std::cout << typeid(exit).name << std::endl; 

while gives weird output functions, may find information can you, best 1 being if 2 types different.

here's working example showing issue @ run-time function pointer casting: http://coliru.stacked-crooked.com/a/47f74e8b6f389812


Comments