質問

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??

役に立ちましたか?

解決

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);
}

他のヒント

The comma operator evaluates both expressions, and returns the value of the last.

  • The first expression does two things in one statement. If chooses 'L' or 'R' and also sets x to its negative if 'L' is chosen.
  • The second expression (the part after the 'if') decrements x and then puts a character. The meaning of this is unclear without more context.

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.

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top