I just have a quick question about the conditional operator. Still a budding programmer here.
I am given x = 1, y = 2, and z = 3.
I want to know, why after this statement:
y += x-- ? z++ : --z;
That y is 5. The values after the statement are x = 0, y = 5, and z = 4.
I know the way the conditional operator works is that it is formatted like this:
variable = condition ? value if true : value if false.
For the condition, y += x– , how does y become 5? I can only see 2 (2 += 0) and 3 (2 += 1)(then x– becomes zero) as possibilities. Any help is much appreciated. 🙂
When it evaluates the condition (x != 0) x is still 1 (that is
not 0). So it picksz++. Which is still 3. 2 + 3 = 5. At the end of the day x has become 0 and z has become 4.Take a look here for details. It’s important to remember a simple thing: when you say
x ++the current value of x is used and then it is incremented. When you say++xit is first incremented and then used.