==============================
== What I have learnt today ==
==============================

The comma operator (almost made me have a coma to understand it.)

I tried to understand the comma operator. I have tried the following small program:

#include <iostream>

int main ()
{

	int j = 0;
	int k = 0;
	j = 4,5;
	k = (4,5);

	std::cout << "j: " << j << std::endl;
	std::cout << "k: " << k << std::endl;

	return 0;
}

The compiler does give some warnings, despite a little bit different:

 warning: expression result unused [-Wunused-value]
    8 |         j = 4,5;
      |               ^

 warning: left operand of comma operator has no effect [-Wunused-value]
    9 |         k = (4,5);
      |              ^     

and the result is:

j: 4
k: 5

That is strange.

My initial understanding of the comma operator is that it

  • returns the value of the expression at the right
  • is the operator with the lowest precedence

After some googling and asking around in reddit, I ended up finding a good explantion of it.

The key mistake is that I have missed the second point. The comma operator has the lowest precedence - that means it is lower than the assignment operator. That is to say,

j = 4,5;

is equivalent to

(j = 4), 5;

C++ first gives the value 4 to the named variable j. Then the comma operator comes into work and evaluate both expressions around it and return the value at his right.

Most of the time, assignment is the last thing happened. So my initial focus is on the comma operator and the brackets around it. So my muscle memory excludes the assignment operator in property 2 of the comma operator. So the complete sentance should be:

Comma operator has the lowest precedence - including the assignment operator

Then everything makes sense.

This is a small lesson or use case from what I have learned fromThink Again

A little spinoff during my little research on the comma operator, is that I have come to know Sequence point.