Whats the difference between using "?" and if statements

Jul 22, 2020 at 9:24pm
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
	}
Jul 22, 2020 at 9:28pm
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 Jul 22, 2020 at 9:30pm
Jul 22, 2020 at 9:32pm
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
Jul 22, 2020 at 9:38pm
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.