Reputation: 81472
Sometimes, when I have a multi-case if
, or a very simple for
, with only two statements, I will forgo braces, instead using the comma. Is this a bad exploitation of the feature, and is it ugly and bad form? Or is it an acceptable way to save time and space?
For example:
if (something)
b = y, c = z--;
instead of:
if (something) {
b = y;
c = z--;
}
Upvotes: 2
Views: 331
Reputation: 754800
It won't save more than a few moments of typing time.
If you really need to save space on screen that much, you need a bigger screen (or you should run a bigger terminal window).
It makes no difference to the object code produced. Therefore, it has no affect on runtime.
It is harder to step through the component statements of a comma expression in a debugger.
I think it is easier to read the colon-separated (and hence 'braced') code, without it being significantly harder to type the braced version. (After the length of time I've been coding in C and using braces, I'd have to think hard to remember to use the comma notation.)
Upvotes: 5
Reputation: 28850
The more a code reader has to look / check the language core details, the less that code is readable. In this case there are two distinct instructions, so the braces usage is, in my opinion, obvious.
What about
a = b, c;
or
a = b, c ? d, e : f, g;
Code readers (most) not used to that syntax, may want to check the ,
precedence to ensure of which value will be assigned.
We expect someone reading a source code to focus on the code logic, not its syntax.
Upvotes: 2
Reputation: 118660
The comma form is more useful for when you cannot use braces:
#define MY_ASSERT(expr) ((expr) || (debugbreak(), 0))
Here debugbreak()
returns void
, but we still wish to have 0
as an rvalue.
Upvotes: 3
Reputation: 2962
I'd vote against it for a few reasons:
Upvotes: 8
Reputation: 215517
I consider it very good style, but I'm sure others will disagree.
One particular variant use of the comma operator is within the parts of a for
statement, as in:
for (i=0, j=1; i<j; i++, j++) { ... }
Upvotes: 4
Reputation: 5383
It's indeed a clever way to use that syntactic feature of most C-like languages.
Personally, I try to stay the least ambiguous as possible when I code, so I always include {
and }
in all of my if
statements. It may save time, but I prefer clarity: it doesn't speed up or slow down the code execution.
Upvotes: 12
Reputation: 6233
I have never used the comma syntax. But this is because I didn't know it existed, to be honest.
If I knew about it, then I would have happily used it in place of annoying braces for a mere two or three statements.
So in my opinion, use at will! Just so long as you don't make that classical mistake:
if (cond)
doSomething();
doSomethingElse(); // <-- oops, unconditional statement!
Upvotes: 1