Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all non-member function pointers the same size in C++

In the C programming language, we are given the guarantee that a function pointer may legally be converted to a function pointer of a different type and back without loss of data:

Section 6.3.2.3, paragraph 8:

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer.

This rule indirectly guarantees that the sizeof one function pointer must be the same as the sizeof any other function pointer, since no loss of data may occur.

However, I am having difficulty finding any similar passages in the C++ standard (currently reading the C++17 standard, if that matters). There are actually few mentions I can find of any conversions to do with function pointers explicitly, but neither conv.ptr nor basic.compound really provide any similar guarantees.

My question is this: Does C++ provide the same guarantee that C does that any (non-member) function pointer may hold the value of any other (non-member) function pointer?


I was hoping to find this already asked, but the closest I could find was this similar question for C (which is not guaranteed to be the same answer as C++), and a bunch of unrelated questions about sizes of member pointers.

To emphasize: This is not asking whether it may work because a compiler supports both C and C++; this is asking whether the C++ abstract machine officially supports this same conversion.

like image 736
Human-Compiler Avatar asked Jan 24 '23 11:01

Human-Compiler


1 Answers

Yes, quoting from expr.reinterpret.cast/6:

A function pointer can be explicitly converted to a function pointer of a different type.

[Note 5: The effect of calling a function through a pointer to a function type ([dcl.fct]) that is not the same as the type used in the definition of the function is undefined ([expr.call]). — end note]

Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

[ EDIT ]   The "yes" part of the answer refers to OP's question as worded in the body of the post: "does C++ provide the same guarantee that C does that any (non-member) function pointer may hold the value of any other (non-member) function pointer?".

As pointed out in @NateEldredge's comments, this does not automatically imply that "all non-member function pointers [are] the same size in C++" (as the title of the question reads), though it would strongly suggest that they do.

like image 173
dxiv Avatar answered Feb 04 '23 13:02

dxiv