hasvn
hasvn

Reputation: 1132

Is this correct C++0x code?

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.

Upvotes: 9

Views: 345

Answers (4)

mloskot
mloskot

Reputation: 38952

Now, it should not even compile. The lambda expression yields a type (a functor). There is no implicit conversion from type to function pointer.

Depending on compiler, main function can have C++ or C linkage (it is implementation defined). Lambda expression returns C++ type with function call operator, thus C++ linkage.

Upvotes: 0

Adam Mitz
Adam Mitz

Reputation: 6043

For portability among compilers and standard library implementations, printf() must be std::printf() when #including <cstdio>. And the other stuff about the invalid main().

Upvotes: 0

6502
6502

Reputation: 114579

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).

Upvotes: 3

avakar
avakar

Reputation: 32685

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.

Upvotes: 14

Related Questions