Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a for loop variable const with the exception of the increment statement?

Consider a standard for loop:

for (int i = 0; i < 10; ++i)  {    // do something with i } 

I want to prevent the variable i from being modified in the body of the for loop.

However, I cannot declare i as const as this makes the increment statement invalid. Is there a way to make i a const variable outside of the increment statement?

like image 541
jhourback Avatar asked Aug 13 '20 16:08

jhourback


People also ask

Can we increment const variable?

The constant variable values cannot be changed after its initialization. In this section we will see how to change the value of some constant variables. If we want to change the value of constant variable, it will generate compile time error.

When increment happens in for loop?

Increment is an expression that determines how the loop control variable is incremented each time the loop repeats successfully (that is, each time condition is evaluated to be true). The for loop can proceed in a positive or negative fashion, and it can increment the loop control variable by any amount.

Can we increment 2 variables in for loop?

Yes, by using the comma operator. E.g. for (i=0, j=0; i<10; i++, j++) { ... }

How do you give a loop in two increment?

A common idiom is to use the comma operator which evaluates both operands, and returns the second operand. Thus: for(int i = 0; i != 5; ++i,++j) do_something(i,j);


1 Answers

From c++20, you can use ranges::views::iota like this:

for (int const i : std::views::iota(0, 10)) {    std::cout << i << " ";  // ok    i = 42;                 // error } 

Here's a demo.


From c++11, you can also use the following technique, which uses an IIILE (immediately invoked inline lambda expression):

int x = 0; for (int i = 0; i < 10; ++i) [&,i] {     std::cout << i << " ";  // ok, i is readable     i = 42;                 // error, i is captured by non-mutable copy     x++;                    // ok, x is captured by mutable reference }();     // IIILE 

Here's a demo.

Note that [&,i] means that i is captured by non-mutable copy, and everything else is captured by mutable reference. The (); at the end of the loop simply means that the lambda is invoked immediately.

like image 131
cigien Avatar answered Sep 22 '22 14:09

cigien