The last answer is wrong because the previous statement change the value of "y" to 0.0. So for the last one "x" has the value 0.0

Quote:

Originally Posted by jmarsh56

Code:

int a = 1;
int b = 2;
a = b++; my answer is a = 2 and b++ = 2

a = ++b; my answer is a = 3 and ++b = 3

These are wrong as well.
"a" does have the value 2 but "b" has the value 3 after the statement finishes.
Now for the second one "b" has the 3 but it is incremented before it is used so it now has the value 4. So "a" has the value 4 and so does "b".

05-02-2006

DougDbug

The thing to remember is:

The value on the right is assigned to the variable on the left.

These things with equal-signs that look like mathematical equations are NOT equations. They are assignment statements.

In just about any programming language, you can write X = X+1. You cannot do that in math!

You can only have one variable on the left*. On the right, you can have a constant, “known” variable, or any expression that computes to a value.

Sometimes X++ and ++X are the same thing. It’s just a matter of precedence (which operation is done first). Look-up prefix and postfix. For example, prefix has higher precedence than the assignment operator (the equal sign). Postfix has lower precedence than the assignment operator.

FYI - In most other situations, you can forget about precedence and use parenthesis to force the desired order of operation. It makes your program easier to read, and helps avoid bugs!

* The variable on the left is often called an L-value. If you get an error message that says something about an L-value (or lvalue), it usually means you did something like 5 = x+1, which is invalid in C/C++, because you cannot assign a new value to 5!