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--;
}
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
or
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.
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.)
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++) { ... }
I'd vote against it for a few reasons:
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:
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 myif
statements. It may save time, but I prefer clarity: it doesn't speed up or slow down the code execution.