The assignment to variable has no effect?

喜欢而已 提交于 2019-12-05 06:32:45

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.

Breaking the statement up you are basically writing:

++count;
count = count;

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!