So I'm messing around with calling functions in C++ since I am still very new to this language and I've been stuck on this error for like 20 minutes and I can't find an answer anywhere. It keeps on giving me the error : error C2601: 'TimesTwo : local function definitions are illegal and the same for my Test function.
#include <iostream>
using namespace std;
int TimesTwo(int num1);
int Test(int a);
int main()
{
int TimesTwo(int num1)
{
int result;
result = num1 * 2;
return result;
}
int Test(int a)
{
int result;
int num1;
cin >> num1;
result = TimesTwo(num1);
return result;
}
return 0;
}
While local function definitions as above are illegal C++ supports local functions by means of lambdas. The following is legal in C++11 and later.
#include <iostream>
using namespace std;
int main()
{
auto TimesTwo = [](int num1)
{
int result;
result = num1 * 2;
return result;
};
auto Test = [&TimesTwo](int a)
{
int result;
int num1;
cin >> num1;
result = TimesTwo(num1);
return result;
};
using fp = int (*)(int);
fp f1 = TimesTwo; // non-capturing lambda can be converted to function pointer.
return 0;
}
A helpful feature of lambdas is that lambdas that do not capture anything can be converted to a function pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With