John Doe
John Doe

Reputation: 43

Using for loop inside declaration of variable

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);
}

Upvotes: 4

Views: 106

Answers (2)

user12450543
user12450543

Reputation:

actually has been prepared by C++ committee..
constexpr has many usefulness not yet exlpored

constexpr int b(int l) {
            int b=0;
            for (int i = 0; i < l; i++)
                b += i;
            return b;
        }

int main() {

    constexpr int a = b(5);

    printf("%d", a);
}

Upvotes: 0

deW1
deW1

Reputation: 5660

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.

Upvotes: 8

Related Questions