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#?
Use a comma after the if-clause when the if-clause precedes the main clause. If I'd had time, I would have cleaned the house. If the main clause precedes the if-clause, no punctuation is necessary. I would have cleaned the house if I'd had time.
In the C and C++ programming languages, the comma operator (represented by the token , ) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). a is evaluated first and discarded, b is evaluated second and returned as 0.
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.
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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With