Multiple statements if condition is true in shorthand if
Asked Answered
S

2

2

I recently discovered the shorthand if statement and after searching online I couldn't find a definite answer.

Is it possible to execute 2 statements if the condition is true/false?

int x = (expression) ? 1 : 2;

for example

int x = (expression) ? 1 AND 2 : 3;

Seeing as i haven't comne across a example where they used it I guess it's not possible but I wouldn't want to miss out.

Suspensory answered 9/6, 2011 at 21:37 Comment(2)
Have you tried it yet, or are you waiting for us to do that for you?Cordero
I'm not sure I understand. You want x to be 1 and 2 at the same time? If you're thinking about nesting ternary if-tests, yes, it is possible.Dayna
P
4

You're talking about conditional assignment. You should look at what is defined by what you've written:

int x = (expression) ? 1 AND 2 : 3;

That is evaluating 'expression' and if true executing '1 AND 2' then assigning the value to x. If 'expression' evaluated to false, '3' is evaluated and assigned to x. Hence you could definitely do something like this:

int x = (expression) ? GetInt1() + GetInt2() : 345;

What is important is that what you have found is not just a shorthand if. It is conditional assignment.

Paternoster answered 9/6, 2011 at 21:40 Comment(1)
it's an assignment to a conditional expression.Stuck
B
0

You can't have a statement return two values and that's all that ternary does. It is not a shorthanded if it is a method persay that returns values

Barrator answered 9/6, 2011 at 21:41 Comment(1)
Statements don't return values at all, expressions do; a ternary expression is an expression, not a statement; and it certainly doesn't return two values. -1Braun

© 2022 - 2024 — McMap. All rights reserved.