What is this strange conditional operator syntax?

I recently saw the following in the codebase:

bool bRes = (a < b) ? a=b, true : false;

If a < b, entonces a=b se ejecuta y bRes is true. What exactly is going on here? The docs for conditional operator don't mention anything about chaining expressions.

edit: to be clear I get the conditional operator part, it's the a=b, true as a single expression that confused me.

preguntado el 31 de julio de 12 a las 13:07

2 Respuestas

Eww. That is a usage of the operador de coma. a=b, true does precisely what you said. It executes each expression and results in the value of the last expression.

Respondido 31 Jul 12, 13:07

+1 Hahahaha... you've not seen a real "eww" use of the comma operator yet. My all-time favorite is in Subbotin's carryless range coder. Just look at that line for less than 30 seconds, and then try to explain what's going on. - Damon

That is a correct code, but written in a strange style. The language allows to use the comma operator this way.

El equivalente es

bool bRes;
if (a < b)
 a = b;
 bRes = true;
 bRes = false;

Respondido 31 Jul 12, 13:07

this is a MUCH better way of writing the same thing. Good job! - Woodrow Douglass

But now it's assignment and not initialization. In the original code, we may well have declared bRes para ser const... - Kerrek SB

@KerrekSB: Good point. How about const bool bRes = a < b; if (bRes) a = b; ? - Andrey

@Andrey: Better! Any code of the sort bool w = condition ? true : falseo es if-equivalent as in your example, should be avoided at all cost. - Kerrek SB

@Andrey: my previous comment is rather about using comma operator inside initializers in general; I agree that this particular example is ugly enough. - user396672

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.