Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 512
Batwoman05 Avatar asked May 04 '18 12:05

Batwoman05


2 Answers

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.

like image 176
Hatted Rooster Avatar answered Nov 15 '22 03:11

Hatted Rooster


Lets break this expression into pieces: A += value, whereas value = B++ == 0. As later cout suggests, value == 1. Why is that? Here is why: value is result of comparison of B++ and 0, but ++ (increment) operation, when written after operand, is being processed after the comparison, i.e. if you write A += ++B == 0 the later cout should (and does) print 0, 1.

like image 44
Binpord Avatar answered Nov 15 '22 05:11

Binpord