A Compiler Gotcha!

I was very surprised to see the following compiled without an error, and give the wrong answer:

int a, b, c, d;
float e;
void setup() {
  a = 5; b = 3; c = 7; d = 0;
  if (a > b)  c = 4, d = 10, Serial.println(d), e = d/c, Serial.println(e);

Not only does the structure seem all wrong (no braces used to enclose multiple statements, but the answer is also wrong for e (2.0 vice 2.5).
It gives correct results for c and d.

I have always thought that only one statement is accepted after a conditional statement unless you use braces.

Thought this might interest someone here.

Look up the "comma operator".

The value printed for "e" is correct.

What do you understand the comma operator does?

An integer divided by an integer gives an integer.

you divide int by int, the result is int, this is why you lose decimal point part. And using comma in if statement and skip braces on multiple statements is not uncommon.

... but it's not common either, unless you got some weird sequence point requirements.

I guess it is down to style of programming, i’ve seen this in production code, but I wouldn’t use it myself and I’m pretty sure most companies would say no to it in programming guidelines

If I were in a code review and saw code like this, it'd be time for a talk out behind the woodshed...

It's the 9600 bits per second serial speed, isn't it?