Reputation: 351
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.
Upvotes: 2
Views: 5161
Reputation: 1774
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
Upvotes: 0
Reputation: 24457
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.
Upvotes: 4