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.

Patrick
  • 351
  • 1
  • 4
  • 15
  • Have you tried it yet, or are you waiting for us to do that for you? – Kyle Sletten Jun 09 '11 at 21:40
  • 1
    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. – whirlwin Jun 09 '11 at 21:41

2 Answers2

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.

Mike Kwan
  • 24,123
  • 12
  • 63
  • 96
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

if_zero_equals_one
  • 1,716
  • 4
  • 17
  • 30
  • 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. -1 – user207421 Dec 10 '13 at 06:11