2
typedef int (*identity_t)(int); 
identity_t retFun() { 
  return [](int x) { return x; };
}

This piece of code works, but why do I need the first line?

Why doesn't the code below work?

int (*)(int) retFun() { 
  return [](int x) { return x; };
}
  • Related: [How to make a function return a pointer to a function? (C++)](https://stackoverflow.com/questions/997821/) – Remy Lebeau Nov 07 '18 at 05:12

2 Answers2

8

The typedef makes it easier to write the function declaration, but you don't need the typedef if you know the right syntax:

int (*retFun())(int) {
    return [](int x) { return x; };
}

As you can see, the typedef not only makes it easier to write; it makes it easier to read as well.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • 2
    Using `auto` would also make it easer to read while still avoiding the typedef: `auto retFun() -> int(*)(int) { ... }` – Remy Lebeau Nov 07 '18 at 05:16
4

C++ syntax inherited from C is weird, counterintuitive and archaic. You need the typefef to cope with the fact.

int (*retFun())(int) { ... } 

is frankly an unreadable mess.

The new crop of the C++ syntax alleviates the problem somewhat.

auto retFun () -> auto (*)(int) -> int { 
   return [](int x) { return x; };
}

The new syntax is written mostly left-to-right, as one would read it.

  auto retFun

"retFun is ..."

  () ->

"... a function that takes no arguments and returns ..."

  auto (*)

"... a pointer to ..."

  (int) -> 

"... a function that takes an int argument and returns ..."

  int

"... an int".

More about function declarations.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243