Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local function definition are illegal

Tags:

c++

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;
}
like image 713
Dinah21599 Avatar asked Jul 01 '26 13:07

Dinah21599


1 Answers

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.

like image 134
Bowie Owens Avatar answered Jul 03 '26 05:07

Bowie Owens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!