Meaning of int (*) (int *) = 5 (or any integer value)
It's a bug in g++.
int (*) (int *)
is a type name.
In C++ you cannot have a declaration with a type name without an identifier.
So this compiles with g++.
int (*) (int *) = 5;
and this compiles as well:
int (*) (int *);
but they are both invalid declarations.
EDIT:
T.C. mentions in the comments bugzilla bug 60680 with a similar test case but it has not yet been approved. The bug is confirmed in bugzilla.
EDIT2:
When the two declarations above are at file scope g++ correctly issues a diagnostic (it fails to issue the diagnostic at block scope).
EDIT3:
I checked and I can reproduce the issue on the latest release of g++ version 4 (4.9.2), latest pre-release version 5 (5.0.1 20150412) and latest experimental version 6 (6.0.0 20150412).
It is not valid C++. Remember that because your particular compiler happens to compile it doesn't make it valid. Compilers, like all complex software, sometimes have bugs and this appears to be one.
By contrast clang++
complains:
funnycast.cpp:3:11: error: expected expression
int (*) (int *) = 5;
^
funnycast.cpp:3:18: error: expected '(' for function-style cast or type construction
int (*) (int *) = 5;
~~~ ^
funnycast.cpp:3:19: error: expected expression
int (*) (int *) = 5;
^
3 errors generated.
This is the expected behavior because the offending line is not valid C++. It purports to be an assignment (because of the =
) but contains no identifier.
As other answers have pointed out, it is a bug that
int (*) (int *) = 5;
compiles. A reasonable approximation of this statement that would be expected to have a meaning is:
int (*proc)(int*) = (int (*)(int*))(5);
Now proc
is a pointer-to-function that expects the address 5
to be the base address of a function that takes an int*
and returns an int
.
On some microcontrollers/microprocessors 5
might be a valid code address, and it might be possible to locate such a function there.
On most general-purpose computers, the first page of memory (addresses 0-1023
for 4K pages) are purposely invalid (unmapped) in order to catch null
pointer accesses.
Thus, while behavior depends on the platform, one can reasonably expect a page fault to occur when *proc
is invoked (e.g., (*proc)(&v)
). Before the time at which *proc
is invoked, nothing unusual happens.
Unless you are writing a dynamic linker, you almost certainly shouldn't be numerically calculating addresses and assigning them to pointer-to-function variables.