1

I need to know what does this for loop syntax actually says.

for(int parity : {0, 1}) {
            int low = 1, high = n;
            if(low % 2 != parity) low++;
            if(high % 2 != parity) high--;
          }
Jarod42
  • 203,559
  • 14
  • 181
  • 302
Tarun
  • 25
  • 4
  • Why is this tagged `competitive-coding` ? Tags should be ...tags, ie if your question is about competitive-coding you can use the tag so that users interested in the topic can find your question easily, but in your question there is no mention at all of competitive coding – 463035818_is_not_an_ai Mar 26 '20 at 08:57
  • not really a duplicate, but still it may answer your question: https://stackoverflow.com/questions/15927033/what-is-the-correct-way-of-using-c11s-range-based-for – 463035818_is_not_an_ai Mar 26 '20 at 08:59
  • 3
    Are you wondering about the "range loop" syntax (it's a decade old by now, so should be covered by any not-ancient book), or about what the loop accomplishes? – molbdnilo Mar 26 '20 at 08:59
  • The loop has no visible side effects (except possibly if `n` is a custom class). – Jarod42 Mar 26 '20 at 09:05
  • 1
    "What does this code do?" is not an answerable question. The code itself is the best description of what it does. Or do you want to be more specific? Does it do something you don't expect? Is there a syntax you want documentation about? – tenfour Mar 26 '20 at 09:06

1 Answers1

0

Alright lets break this line by line.

for (int parity : {0,1}) {

results in:

for (int parity : std::initializer_list<int>{0, 1}) {

initializer_list<int>{0,1} has two elements so the for loop will loop two times

low is assigned 1, high is assigned n which I assume is the high end?

if(low % 2 != parity)

will result in 1 on the first iteration so the value of low will become 2;

likewise high will decrease/increase its value depending upon the value of n

at the end of loop low will be equal to 3, the value of high will depend upon the value of n which is unknown in this context.

Waqar
  • 8,558
  • 4
  • 35
  • 43
  • 2
    *"at the end of loop low will be equal to 3"*. No, `low` is reset to 1 at start of the loop iteration, and can only be incremented once by loop iteration. In addition, once loop ends, those variables ends too. – Jarod42 Mar 26 '20 at 10:06
  • Ah yes, my bad. Low is being reinitialized on every iteration – Waqar Mar 26 '20 at 12:37