Farnsworth
Farnsworth

Reputation: 125

What does this C++ for-loop expression mean?

I am working through the "Add Binary" problem on leetcode and a solution which I found online is the following:

#include <string>
using std::string;

class Solution {
public:
    string addBinary(string a, string b) {
        string ret;
        bool carry{false};
        for (auto apos=a.size(), bpos=b.size(); apos || bpos || carry; ) {
            bool abit{apos && a[--apos] == '1'};
            bool bbit{bpos && b[--bpos] == '1'};
            ret = (abit ^ bbit ^ carry ? "1" : "0") + ret;
            carry = abit + bbit + carry >= 2;
        }
        return ret;
    }
};

My question is regarding the for loop above. I understand that two iterations are being instantiated with the first two expressions that are separated by a comma. However, I don't understand how the three units being or'd (ie: ||) is supposed to behave. I'm also curious why it's ok to exclude the iterator expression in this instance, ie the final expression in the for-loop. Please help me to understand how this code functions.

Upvotes: 2

Views: 188

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122298

Sometimes it helps to consider the equivalent while loop:

for (auto apos=a.size(), bpos=b.size(); apos || bpos || carry; /*no increment*/) {
    // ...
}

->

{
    auto apos = a.size();
    auto bpos = b.size();
    while( apos || bpos || carry ) {
        bool abit{apos && a[--apos] == '1'};
        bool bbit{bpos && b[--bpos] == '1'};
        ret = (abit ^ bbit ^ carry ? "1" : "0") + ret;
        carry = abit + bbit + carry >= 2;
        /* increment would be here*/
    }   
}

The loop initializes apos and bpos and continues to loop as long as the condition apos || bpos || carry yields true, ie as long as apos, bpos and carry are not all 0 (0 is converted to false any other number to true).

Upvotes: 0

mss
mss

Reputation: 1493

basically the for loop consist of 3 parts separted by ';'(semi-colon)
1)first part, this part is about initialization of variables, again you can leave it if you want
2)second part, it defines the condition on basis of which for loop will keep running, again you can leave it if you want
3) third part, this is the part where you want to do some operations, conventially iteration value is increment, but again you can leave it if you want

so if you go with this model, I think you can easily break down what is happening in the for loop that you mentioned.

Upvotes: 1

Related Questions