I'm trying to use a conditional statement that does one thing in one condition but does two things if the other condition applies.
Consider the following:
( h >= 0 && h < 24 ? hour = h : hour = 0, cout << "Invalid Hour Detected\n")
If "h" is set to 25, it sets "hour" to 0 correctly. If "h" is set to 12, it correctly sets "hour" to 12.
The problem is that it outputs "Invalid Hour Detected" for both true and false conditions. I only want it to output if the conditions aren't met.
Essentially, I'm wondering if it is possible in a conditional statement to do two things for one condition.
Also tried:
( h >= 0 && h < 24 ? hour = h : hour = 0 && cout << "Invalid Hour Detected\n")
but that didn't run the cout on either case.
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.
C static code analysis: Conditional operators should not be nested.
The conditional operator (? :) is a ternary operator (it takes three operands).
Conditional OperatorsThe logical AND and logical OR operators both take two operands. Each operand is a boolean expression (i.e., it evaluates to either true or false). The logical AND condition returns true if both operands are true, otherwise, it returns false.
If you really want to do this, add proper parentheses and invert the order of the assignment and the output insertion (when using the comma operator, the value of the left expression is discarded):
( h >= 0 && h < 24 ) ? ( hour = h ) : (std::cout << "Invalid Hour Detected\n", hour = 0);
However, my advice is to make your code readable and abandon this kind of coding style.
I'm trying to use a conditional statement that does one thing in one condition but does two things if the other condition applies.
That's not a conditional statement, it's a conditional expression+. Conditional statement would be a lot more appropriate here from the readability perspective:
if( h >= 0 && h < 24) {
hour = h;
} else {
hour = 0;
cout << "Invalid Hour Detected\n";
}
if
.
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