Search code examples
c++arithmetic-expressionspost-increment

What does this arithmetic expression mean: A += B++ == 0 in C++;


I came accross this expression, and can't understand the meaning of line 3 in the following snippet:

int A=0, B=0;
std::cout << A << B << "\n"; // Prints 0, 0
A += B++ == 0; // how does this exp work exactly? 
std::cout << A << B << "\n";  // Prints 1, 1

A adds B to it, and B is Post incremented by 1, what does the "==0" mean?

Edit: Here's the actual code:

int lengthOfLongestSubstringKDistinct(string s, int k) {
    int ctr[256] = {}, j = -1, distinct = 0, maxlen = 0;
    for (int i=0; i<s.size(); ++i) {
        distinct += ctr[s[i]]++ == 0; // 
        while (distinct > k)
            distinct -= --ctr[s[++j]] == 0;
        maxlen = max(maxlen, i - j);
    }
    return maxlen;
}

Solution

  • B++ == 0 
    

    This is a boolean expression resulting in true or false. In this case the result is true, true is then added to A. The value of true is 1 so the (rough) equivalent would be:

    if(B == 0)
      A += 1;
    ++B;
    

    Note that this isn't particulary good or clear to read code and the person who wrote this should be thrown into the Gulags.