Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using for loop inside declaration of variable

Tags:

c++

Can I use for loop inside declaration a variable?

int main() {
    int a = {
        int b = 0;
        for (int i = 0; i < 5; i++) {
            b += i;
        }
        return b;
    };

    printf("%d", a);
}
like image 548
John Doe Avatar asked Jan 25 '23 09:01

John Doe


1 Answers

You can use a lambda:

int main() {
    int a = []{
        int b = 0;
        for (int i = 0; i < 5; i++) {
            b += i;
        }
        return b;
    }();

    printf("%d", a);
}

It's important to note that you have to immediately execute it otherwise you attempt to store the lambda. Therefore the extra () at the end.

If you intent to reuse the lambda for multiple instantiations, you can store it separately like this:

int main() {
    auto doCalculation = []{
        int b = 0;
        for (int i = 0; i < 5; i++) {
            b += i;
        }
        return b;
    };

    int a = doCalculation();

    printf("%d", a);
}

If you need it in more than one scope, use a function instead.

like image 195
deW1 Avatar answered Feb 05 '23 00:02

deW1