Reputation: 155
I was going through someone elses code and I wasn't able to get the syntax of following
c = x<0 ? x = -x,'L':'R';
and
if(x) x--,putchar(c);
going by the symantics, it is clear that in the first, variable c is assigned 'L' or 'R'.And in the second, both x-- and putchar() are executed. But what exactly is the role of comma operator here??
Upvotes: 1
Views: 260
Reputation: 46249
But what exactly is the role of comma operator here?
In this case, code obfuscation. The original developer probably thought they were being clever.
The comma operator allows you to perform multiple actions in a single statement, but you are almost always better off using 2 statements. In those cases, it expands to:
if( x < 0 ) {
x = -x;
c = 'L';
} else {
c = 'R';
}
and
if(x) {
x--;
putchar(c);
}
Upvotes: 5
Reputation: 86381
The comma operator evaluates both expressions, and returns the value of the last.
Readability in both could be improved by using separate statements rather than the comma operator. The first tries to shoehorn an if
statement into a conditional expression. But the second is already using an if
statement, so it's unclear why the comma operator was chosen at all.
Upvotes: 5
Reputation: 126412
The role of the comma operator in that context is to allow using the conditional operator and write an assignment as part of the evaluation of one of the expressions.
In my opinion, this is just horrible style. An if
statement would have better communicated the intent of that code, and would have hardly been less efficient.
Upvotes: 2