4

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);
}
1
  • 2
    Use a function/lambda. Commented Jan 18, 2020 at 18:46

2 Answers 2

8

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.

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

4 Comments

Thanks! What about I want to have another declaration of variable above a (unsigned char x = 7) and I want to return x*b. It gets me error: void value not ignored as it ought to be and error: ‘x’ is not captured.
You need to capture it e.g. [x]{ but it's hard to say without code. Please read some more about lambdas and captures, e.g. here en.cppreference.com/w/cpp/language/lambda or simply google the term, then you will find many tutorials
Thanks a lot! I just didn't know the term.
We are not talking about declaration here, even not definition. We are talking about initialization, and especially about copy initialization. Please see here: en.cppreference.com/w/cpp/language/copy_initialization . But tons of upvotes and an accepted answer, so everything perfectly OK. +1 from my end. If we would be strict: The only correct answer to the given question is simply: "No, not possible"
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.