Increment and Decrement Operators

How valid and invalid below, as shown and what they mean. When such a situation arises, to write this piece of code.

++x = 5; // legal --x = 5; // legal x++ = 5; // illegal x-- = 5; // illegal 
+6
c ++
source share
7 answers

Postfix (x ++ / x--) statements do not return lvalue (a value you can assign).

They return a temporary value, which is a copy of the value of the variable before changing

Value is the value of r, so you can write:

y = x++ and get the old value of x

+13
source share

Given that both operators = () and operator ++ () can be overloaded, it is impossible to say what the code does without knowing more about the type of things to which the operators apply.

+9
source share

All of them change the value of x more than once between points in the sequence and therefore undefined behavior that should be avoided. I don’t see where the distinction between “legal” and “illegal” occurs, because the behavior is legal, any behavior (including sending sorted email to the Secretary of State) is fully consistent with the Standard.

+7
source share

Assuming the question is about the built-in operators ++ and -- , none of these statements are strictly legal.

The first two are well formed, i.e. just compiled because the result of the prefix increment is lvalue. The last two are poorly formed, since the result of the postfix increment is not an rvalue value, so you cannot assign it to it.

However, even the first two are not legal in a sense that they give rise to undefined behavior. You cannot change the same object more than once without an intermediate point. (Note also that compilers are allowed to refuse to compile well-formed code that creates undefined behavior, which means that even the first pair may not be compiled).

+5
source share

++x and --x both return x (after they have been increased / decreased). At this point, you can do what you want with it, including assigning a new value to it.

x++ and x-- both will return to you what x was (just before it was enlarged / reduced). Changing this value does not make sense than changing any return value of a regular function:

 obj->getValue() += 3; // pointless 
+2
source share

Honestly, you should never write this. Post-increment and pre-increment (and decrements) should only be used on their own. They are just recipes for confusion.

+1
source share

The only place I can think about where such a situation will occur is operator overloading with operator ++ and operator =. Even then, the definition is not clear. What you say basically adds one to x and then assigns it to 5. The question is: why do you need to increase x to assign it 5? The only possible explanation is if you have some class in which the ++ operator somehow increments the internal counter, then assignment. I don’t know why this is necessary.

+1
source share

All Articles