Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment and Decrement operators

Tags:

c++

How are the below valid and invalid as shown and what do they mean. When would such a situation arise to write this piece of code.

++x = 5;     // legal
--x = 5;     // legal
x++ = 5;     // illegal
x-- = 5;     // illegal
like image 996
ckv Avatar asked May 06 '10 17:05

ckv


People also ask

What is increment and decrement operator with example?

In programming (Java, C, C++, JavaScript etc.), the increment operator ++ increases the value of a variable by 1. Similarly, the decrement operator -- decreases the value of a variable by 1. a = 5 ++a; // a becomes 6 a++; // a becomes 7 --a; // a becomes 6 a--; // a becomes 5. Simple enough till now.

What is ++ i and i ++ in C?

In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent.

What is the difference between increment and decrement operators?

Increment Operator adds 1 to the operand. Decrement Operator subtracts 1 from the operand. Postfix increment operator means the expression is evaluated first using the original value of the variable and then the variable is incremented(increased).

How do you solve increment and decrement operators?

It is used to increment the value of a variable by 1. It is used to decrease the operand values by 1. The increment operator is represented as the double plus (++) symbol. The decrement operator is represented as the double minus (--) symbol.


1 Answers

The postfix (x++/x--) operators do not return an lvalue (a value you can assign into).

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

The value is an rvalue, so you could write:

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

like image 170
Uri Avatar answered Oct 20 '22 15:10

Uri