conditional operators...

how would i translate this code to an if/else statement?
the second code who see there is what i have but i dont know if it's correct
1
2
3
4
5
6
7
8
  total += count == 1 ? sales : count * sales;



if (count ==1)
total +=sales
else
total +=count *sales;
Last edited on
It's rather far from correct. In the ?: operator the condtion is to the left, and if, else are to the right, separated with colon. That's just it. Enclose the three sections of code with parenthesis and you have your if - else statement:
(condition) ? ( if true) : (if false).
Your example may be confusing, but don't get mislead - you CAN use += statement as part of condition.
Last edited on
There is no value to the if/else statement here, and it can only serve to slow down the code.

Just do this:

 
total += count * sales;


If count is 1, then count*sales == sales, so there is no reason to do a conditional here.
so wait im confused so when i changed the conditional operators to if/else statement thats incorrect? by the way i got that conditional operator example from my book
@ OP: C\C++ is pretty big on that whole order of operations thing.
@Blank, your conversion was totally correct. Somehow as Disch pointed out the original statement does not make a lot of sense ( at least supposing we are using integers and default operators ).

And if it was not clear to someone operator ?: is just above assignment in priority.
Last edited on
oh alright thanks everybody for the help, i appreciate it.
@ snowright: Regardless of assignment vs. comparison conditional operator order, multiplication will always be performed before addition so the entire test is redundant.
Last edited on
@Computergeek01, I see no point what so ever in your comment. Did you read the thread or even my post?
Topic archived. No new replies allowed.