The assignment to variable has no effect?
Asked Answered
M

4

8

When I do this: count = ++count; Why do i get the warning - The assignment to variable count has no effect ? This means that count is incremented and then assigned to itself or something else ? Is it the same as just ++count ? What happens in count = count++; ? Why don't I get a warning for this ?

Macleod answered 24/7, 2012 at 21:24 Comment(0)
B
14

count++ and ++count are both short for count=count+1. The assignment is built in, so there's no point to assigning it again. The difference between count++ (also knows as postfix) and ++count (also known as prefix) is that ++count will happen before the rest of the line, and count++ will happen after the rest of the line.

If you were to take apart count=count++, you would end up with this:

    count = count;
    count = count+1;

Now you can see why postfix won't give you a warning: something is actually being changed at the end.

If you take apart count=++count, you would end up with this:

    count = count+1;
    count = count;

As you can see, the second line of code is useless, and that's why the compiler is warning you.

Blanketing answered 24/7, 2012 at 21:25 Comment(4)
I said short for, not identical to.Blanketing
Right - you're answer was more brief when I made that comment (referring to the value returned by the expression). You turned out a great explanation here +1Ancon
why doesn't it through a warning for the first line in the count = count++ example? because that isn't doing anything.Manger
To be honest, I don't know. My answer satisfied OP and I at the time, but in retrospect, I have no idea why prefix would trigger the warning and postfix wouldn't. Sorry.Blanketing
C
3

Breaking the statement up you are basically writing:

++count;
count = count;

As you can see count=count does nothing, hence the warning.

Coracorabel answered 24/7, 2012 at 21:27 Comment(0)
A
3

the ++ operator is a shortcut for the following count = count + 1. If we break your line count = ++count it responds to count = count+1 = count

Arianaariane answered 24/7, 2012 at 21:27 Comment(0)
T
3

To expand a little, count++ is postfix. It takes place after other operations so if you did something like

int a = 0, b = 0;
a = b++;

a would be 0, b would be 1. However, ++count is prefix if you did

int a = 0, b = 0;
a = ++b;

then a and b would both be 1. If you just do

count++;

or

++count;

then it doesn't matter, but if you are combining it with something else, it will

Tic answered 24/7, 2012 at 21:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.