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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With