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.
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.
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.
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.
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.
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.
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