简体   繁体   中英

Return statement in conditional operator

I have a code segment as follows:

if(a < b)
{
    x = y;
    return w;
}
/* all unrelated variables above*/
x = something;
y = something;
/*both x and y from above*/

x and y are global variables, and they are modified inside the if part, I need to assign y to x and then return w, or simply a constant.

I need to use a ternary operator to replace the if part:

I tried the following:

return (((a < b) ? (x = y, w) : 1), (x = something, y = something));

But, I don't seem to get the desired result. I know it is wrong. This is because I used the return stement from a similar expression, that is:

if(x < y)
    return (x = y);
return 1;

Which I wrote as:

return ((x < y) ? x = y : 1);

But, how do I return a value, that involves a prior assignment of a completely different variable in a ternary operator?

The solution suggested by Mankarse:

return (a < b) ? (x = y, w) : (x = something, y = something, z);

Is actually equivalent to:

if (a < b) {
    x = y;
    return w;
}
/* all unrelated variables above*/
x = something;
y = something;
return z;

The second return statement is important.

You cannot conditionally return from the middle of an expression, because return is a statement, you have to return the whole expression. So it really depends on how you want to proceed after the assignment to the y. Or if you really need to change the order of execution in the middle of an expression, you can throw an exception, but that, I guess, would be too complicated in this case.

Put the code block inside a function.

function f(){
x = y;//assumes x, y and w are global.
return w;
}

Then use the function in the conditional statement.

(a < b) ? f() : "value to return if a>=b";

You don't need to put return before a conditional statement since automatically returns 1 of the value, depends on the evaluation of the condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM