Comma instead of semicolon

Yesterday I noticed that:

if(button){
  toggle = 1;
  led = 1;
}

Can be written as:

if(button){
  toggle = 1, led = 1;
}

Which in turn can be written as:

if(button) toggle = 1, led = 1;

I prefer this last way, since it takes less lines (on my tiny monitor).

Can you just replace semicolons with commas like this? Does it always work? Are there any drawbacks to this?

Can you just replace semicolons with commas like this?

No.

Does it always work?

No. The comma operator performs a specific function. You should look up what that function is.

Are there any drawbacks to this?

Yes. It makes your code unreadable.

if(button) { toggle = 1; led = 1; }

does the same thing, correctly.

``

PaulS:

if(button) { toggle = 1; led = 1; }

does the same thing, correctly.

The arduino auto-format wipes this out to:

if(button){
  toggle = 1;
  led = 1;
}

again, and I really like to use that..

Anyway, I looked up the it's function like you said, and there I found:

Avoid a block
For brevity, the comma can be used to avoid a block and associated braces, as in:

if (x == 1) y = 2, z = 3;
if (x == 1)
    y = 2, z = 3;

instead of:

if (x == 1) {y = 2; z = 3;}
if (x == 1) {
    y = 2; z = 3;
}

So that's the contrary of what you said, but it does answer my question..

Inevitableavoidance:
Anyway, I looked up the it's function like you said, and there I found:

Avoid a block
For brevity, the comma can be used to avoid a block and associated braces, as in:

if (x == 1) y = 2, z = 3;

if (x == 1)
    y = 2, z = 3;

Please give a link to the source. Would like to read about it. Thanks!

For brevity, the comma can be used to avoid a block and associated braces

I guess, for the special case of assignments. What the comma operator actually DOES is quite different than what a semicolon does, so it would be very dangerous to assume that you could switch them in general.

There is no particular reason to ever "avoid a block and associated braces."

The inability to defeat the auto-formatter's use of excessive vertical space is a bit unfortunate :frowning:

The inability to defeat the auto-formatter's use of excessive vertical space is a bit unfortunate

The only problem that I have with the auto formatter in the IDE is the way it deals with array declarations.