Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Syntax - Separating statements with , instead of ; legal?

I just ran into this piece of code that does this :

delete a, a = 0;

It compiles and runs just fine. But isn't this supposed to be :

delete a;
a = 0;

Why is separating statements using , allowed in this case ?

Thanks :)

like image 887
Anonymous Avatar asked Nov 16 '11 09:11

Anonymous


People also ask

What is comma operator in C with example?

The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.

What is the use of comma factor in for loop in C?

The comma operator is intended for cases where the first operand has some side effects. It's just an idiom, meant to make your code more readable. It has no effect on the evaluation of the conditional.

What is the purpose of comma operator?

The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.

What is comma C++?

1) Comma as an operator: The comma operator (represented by the token, ) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type).


1 Answers

In C and C++, most "statements" are actually expressions. The semicolon added to an expression makes it into a statement. Alternatively, it is allowed (but almost always bad style) to separate side-effectful expressions with the comma operator: the left-hand-side expression is evaluated for its side-effects (and its value is discarded), and the right-hand-side expression is evaluated for its value.

like image 139
ibid Avatar answered Nov 05 '22 08:11

ibid