# c++ questions

• 05-02-2006
jmarsh56
c++ questions
i have a few c++ questions. i will write down what the question is and my answer. i am just looking to see if i am correct.

int I = 20;
int k = 15;
int j = 5;
j = k; my answer is j = 15
k = j; my answer is k = 5
j = I; my answer is j = 20

double x = 31.2;
double y = 43.2;
double z = 0.0;
x = z; my answer is x = 0.0
y = z; my answer is y = 0.0
x = y; my answer is x = 43.2

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

are these correct?

thanks
• 05-02-2006
Anubis
Quote:

Originally Posted by jmarsh56
Code:

```int I = 20; int k = 15; int j = 5; j = k; my answer is j = 15 k = j; my answer is k = 5 j = I; my answer is j = 20```

I would say you are wrong.
After the first statement "j" has the value of 15.
Now the second statement "k" has the value 15 because "j" just changed in the above statement.
Last "j" has the value 20.
Quote:

Originally Posted by jmarsh56
Code:

```double x = 31.2; double y = 43.2; double z = 0.0; x = z; my answer is x = 0.0 y = z; my answer is y = 0.0 x = y; my answer is x = 43.2```

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!
• 05-03-2006
jmarsh56
thanks for the help now i am starting to understand this more