Whats the difference between using "?" and if statements

So as per the title i'm having time trying to find the difference between using "?" and if statements. Is one considered proper format or does one have potential limitations?

1
2
3
4
5
6
7
8
9
10
int x = 10, b = 5;
	(x > b) ? true : false;
	if (x > b)
	{
		true
	}
	else (b > x)
	{
		false
	}
Both are overkill. Just use
bool result = x > b;


Neither make much syntactical sense, and the second one (presumably) doesn't tell you what happens if b == x.
Last edited on
Hello SO AP,

They are both basically the same. x > b ? true : false; is a shorter if statement, but can only do 1 thing, I believe, whereas what is between the {}s of the if/else can have more than 1 line.

There is a time and place depending on what you want to do.

BTW lines 5 and 9 are missing the (;) at the end of the line.

Andy
A ternary expression is generally more difficult to read than the equivalent if-else block. Not always, just usually.
Topic archived. No new replies allowed.