Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this correct C++0x code?

Tags:

c++

c++11

lambda

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.

like image 880
hasvn Avatar asked Sep 28 '11 12:09

hasvn


2 Answers

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.

like image 64
avakar Avatar answered Sep 27 '22 18:09

avakar


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

like image 35
6502 Avatar answered Sep 27 '22 20:09

6502