Tried this in GCC 4.6 and it compiles and links, but gives a "bus error" message on runtime on MacOS. VS2010 doesn't even compile it.
But the question is, should this actually work in standard C++0x?
#include <cstdio>
int (*main)()=[]()->int{printf("HEY!\n");return 0;};
Yes, what it's trying to do is to define "main" as a lambda function.
This is not a valid C++ program, because the symbol main
is not defined to be a function, but rather a pointer to function. That's why you get segmentation fault -- the runtime is attempting to execute a pointer.
No, this is not correct.
Main is a special function and there are strict requirements for it (even more strict than a regular function), but you are also making some confusion between what is a function and what is a pointer to a function.
The logical problem is that there is a difference between a function and a variable holding a pointer to a function (what you want main to be). A function has a fixed address in memory, so to call a function that address is simply called. A pointer to a function points to an address in memory, so to call the function you need first to read what the pointer is pointing to and then call that address.
A pointer to function has a different level of indirection from a function.
The syntax is the same... i.e. if x
is a pointer to a function you can write x(42)
, but still the generated machine code is different if x
is instead a function (in the case of a pointer a value must be looked up and the call address is determined at run time, with a function the address is fixed - up to relocation - and is determined at link time).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With