sig_seg_v
sig_seg_v

Reputation: 570

In C, what is the difference between comma and semicolon for statements that are discarded

I ask because as I was perusing the source code for grep, I noticed that it uses an element of C syntax, the comma, in a way that I'm not used to seeing it, for example:

r = links[depth], l = r->llink, t = l->rlink;
rl = t->rlink, lr = t->llink;
t->llink = l, l->rlink = lr, t->rlink = r, r->llink = rl;

I researched the usage, and found:

When used as an operator, the comma operator uses the following syntax:

expr1, expr2

The left operand expr1 is evaluated as a void expression (i.e. it is ignored if not contain side effects), then expr2 is evaluated to give the result and type of the comma expression. So, the result is just expr2.

(source: http://tigcc.ticalc.org/doc/opers.html#comma)

So if the comma operator is really "the same" as a semicolon (assuming, of course, that we don't need to use the return value of the expression), in that writing

f(2); g(3);

is functionally equivalent to writing

f(2), g(3);

or even

f(2), g(2),

why do we use the semicolon instead? Why didn't the grep authors just follow convention and use semicolons instead of commas, since C ignores whitespace so newlines are irrelevant??

Very puzzling.

Upvotes: 2

Views: 1059

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754100

In the code shown, the commas could be replaced with semi-colons and there'd be no difference in the way the code worked. It is probably just a way to emphasize how closely related the three operations are.

There are times, though, when the difference is important. For example:

if (links[depth] != 0)
    r = links[depth], l = r->llink, t = l->rlink;

vs:

if (links[depth] != 0)
    r = links[depth]; l = r->llink; t = l->rlink;

Despite the way it's written, the compiler sees:

if (links[depth] != 0)
    r = links[depth];
l = r->llink;
t = l->rlink;

which is not the same thing at all. It also matters in the loop initialization and reinitialization sections of a for loop:

int i, j;
…
for (i = 0, j = max; i < j; i++, j--)

You can't replace those commas with semicolons.

Upvotes: 4

Related Questions