简体   繁体   English

在变量声明中使用 for 循环

[英]Using for loop inside declaration of variable

Can I use for loop inside declaration a variable?我可以在声明变量时使用 for 循环吗?

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

    printf("%d", a);
}

You can use a lambda:您可以使用 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.请务必注意,您必须立即执行它,否则您将尝试存储 lambda。 Therefore the extra () at the end.因此在末尾添加了额外的()

If you intent to reuse the lambda for multiple instantiations, you can store it separately like this:如果您打算将 lambda 重用于多个实例化,您可以像这样单独存储它:

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.如果您需要在多个范围内使用它,请改用函数。

actually has been prepared by C++ committee..实际上已经由C++委员会准备..
constexpr has many usefulness not yet exlpored constexpr有很多用处还没有被发掘

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM