Victor
Victor

Reputation: 153

Confusing use of a comma in an 'if' statement

I have this piece of code in C++:

ihi = y[0]>y[1] ? (inhi=1,0) : (inhi=0,1);

But how would it look in C#?

Upvotes: 13

Views: 1758

Answers (3)

hlovdal
hlovdal

Reputation: 28198

The comma operator evaluates the arguments in turn and then returns the last evaluated expression. I.e. if you had the following code

int four = 2 + 2, mul(2,2), 4;

a strictly-following-the-specification non-optimizing compiler would first add 2 and 2 and then discard the result, then call the function mul and discard the return value and finally evaluate 4 which then is assigned to the i variable.

Notice that after each comma there is a sequence point, so all side effects of the previous evaluations will have been performed. E.g. in

ihi = y[0]>y[1] ? (inhi=1,0) : (inhi=0,1);

the assignment to inhi is done and finished before ihi is updated. And it also means that a compiler can not optimize away the call to mul in the example above unless it knows 100% for sure that the mul function does not have any side effects other than returning a value. That is normally not something the compiler knows, although in C++ it is possible to mark functions as const by which the compiler is told so.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838416

It means this:

if (y[0]>y[1])
{
    inhi = 1;
    ihi = 0;
} else {
    inhi = 0;
    ihi = 1;
}

Or written another way (in C++):

inhi = (y[0]>y[1]);
ini = !inhi;

Upvotes: 14

Jesse Beder
Jesse Beder

Reputation: 34054

The comma operator binds lower than assignment, so the expression

inhi=1,0

sets inhi to 1, and then returns 0. Likewise

inhi=0,1

sets inhi to 0 and returns 1. This whole thing is equivalent to

if(y[0] > y[1]) {
   inhi = 1;
   ihi = 0;
} else {
   inhi = 0;
   ihi = 1;
}

I'd suggest rewriting it this way, if you can. inhi and ihi seem to have the same purpose (in this statement), and the combination ternary operator (?:) and comma operator that you've got give them different weight.

Upvotes: 9

Related Questions