-1
// Example program
#include <iostream>
#include <string>

void Do()
{
    std::cout << "Hello";
}

int Call(int(*f)())
{
    return f();
}

int main()
{
    // WHY DOES THE FOLLOWING COMPILE???!!! 
    // NOTE THE MISSING RETURN STATEMENT
    Call([]()->int{ Do(); });
}

It seems for some compiler, the code above compiles fine, and it also works. But apparently, the lambda is missing the return statement. Why does this work? Is it a problem with the compiler? What does the lambda return in this case?

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
jahithber
  • 99
  • 8

2 Answers2

1

It has more to do with how a function returning an integer is allowed to not have a return statement. This doesn't really have much to do with lambda.

See the following on this topic: Why does flowing off the end of a non-void function without returning a value not produce a compiler error?

jahithber
  • 99
  • 8
0

Lambda expression returns closure with defined call function operator as body of lambda. In your case this call function operator returns int, so it may look like:

class unnamedClass {
  int operator()() const
  {
    Do();
  } // return is missing here
};

and it is undefined behaviour according to reference.

Flowing off the end of a value-returning function (except main) without a return statement is undefined behavior.

Compiler compiles it, but it leads to UB. On g++ i got warning warning: no return statement in function returning non-void [-Wreturn-type].

So if you want your code to work correctly, you need add return.

rafix07
  • 20,001
  • 3
  • 20
  • 33
  • Thanks for looking into this. I wonder why it is a warning instead of a compile error. In what case would the warning be preferred over a compile error? Do you know why this is done this way? I ran into this situation as a bug, so I want to see if there is anything to prevent this from happening in the future. – jahithber Mar 05 '19 at 06:25
  • Found this: https://stackoverflow.com/questions/1610030/why-does-flowing-off-the-end-of-a-non-void-function-without-returning-a-value-no – jahithber Mar 05 '19 at 06:54
  • It leads to UB *if* `Do();` returns normally (instead of e.g. throwing). – HolyBlackCat Mar 05 '19 at 06:57