Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, then a=b is executed and 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.

like image 802
nolegs Avatar asked Jul 31 '12 12:07

nolegs


People also ask

What is the syntax of conditional operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

What is the syntax of conditional statement?

The syntax for if statement is as follows: if (condition) instruction; The condition evaluates to either true or false. True is always a non-zero value, and false is a value that contains zero.

What Is syntax for conditional operator in C?

Syntax of conditional operator in CThe expression will be treated as a logical condition, and any non 0 value will be considered as true, and 0 as false. The statement1 and statement2 can be a statement, expression, variable, or a constant.

What is conditional operator in C with examples syntax?

Example: C Ternary Operator age >= 18 - test condition that checks if input value is greater or equal to 18. printf("You can vote") - expression1 that is executed if condition is true. printf("You cannot vote") - expression2 that is executed if condition is false.


1 Answers

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

like image 161
D.Shawley Avatar answered Sep 24 '22 02:09

D.Shawley