thekingisback's blog

By thekingisback, history, 2 months ago, In English

In some cases, I could write like this:

If(f==true)a++,b++;

Instead of

If(f==true){a++;b++;}

However, sometimes I can't write like that and the compiler showed errors, can anybody teach me how to use the comma properly? I think it will improve my coding speed by alot. Thanks.

  • Vote: I like it
  • +4
  • Vote: I do not like it

»
2 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by thekingisback (previous revision, new revision, compare).

»
2 months ago, hide # |
 
Vote: I like it +12 Vote: I do not like it

the comma can't be placed before keywords like return, break and continue

»
2 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Sometimes I encounter similar problems when writing code relatively quickly; perhaps exploring this issue together would be quite interesting.

»
2 months ago, hide # |
Rev. 2  
Vote: I like it +7 Vote: I do not like it

Long story short, the comma operator can be placed between two expressions forming a new expressions which yields the result of the right expression (including void); both expressions get evaluated, but the left one gets discarded. The comma operator can be chained as well, leading to one big expression which yields the result of the rightmost expression. Anything you can put in the branches of a ternary/conditional operator can be put in the expressions surrounding the comma operator (and vice versa).

Maybe a clearer way to see what can be put in it is noting how said expressions are the $$$\text{same}^1$$$ expressions that can appear inside the condition portion of an if statement. For example, if(return 0){} wouldn't make sense, but if(f() + i++){} would.

Note that the comma operator is distinct from the commas used in function calls; the former is sequenced (evaluates all expressions in order from left to right), while the latter is implementation-defined if I recall correctly.

For more information pertaining to the comma operator, I recommend this page on C++ Reference (a great resource for information pertaining to C++).

$$$\phantom{.}^1$$$: There is technically a difference. The condition of an if statement requires the result of the expression to be convertible to a boolean, whereas comma operator in general has no requirements on the type of the evaluated expression (it can even be void). If statements also technically allow for declaring variables, which is distinct from expressions. More information can be found here.