2

Is it possible to somehow declare and assign a function to function pointer func in main() without having an actual function add()?

Current Code:

#include <iostream> int add(int a, int b) { return a + b; } int main() { typedef int (*funcPtr)(int a, int b); funcPtr func = &add; std::cout << func(2,3) << std::endl; } 

Preferred Style: (if possible)

#include <iostream> int main() { typedef int (*funcPtr)(int a, int b); funcPtr func = (funcPtr){return a + b}; // is something like this possible? std::cout << func(2,3) << std::endl; } 

Is there a way to assign a function to function pointer dynamically like my last code?

5
  • What would you be assigning? Commented Jul 13, 2019 at 15:23
  • @stark so I can pass it to another function Commented Jul 13, 2019 at 15:25
  • I didn't ask "why". Commented Jul 13, 2019 at 15:26
  • @stark Oh, I don't know what what you mean then. I'm trying to assign a function to a function pointer like I wrote. Commented Jul 13, 2019 at 15:28
  • Sounds like what you want is closer to const auto func = [](const auto a, const auto b){ return a + b; }; Commented Jul 13, 2019 at 15:31

1 Answer 1

5

You can use lambda; which could convert to function pointer implicitly if capture nothing.

funcPtr func = [](int a, int b) {return a + b;}; 

LIVE

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.