1

How does +variable operate or +(+variable) operate?

int i=0;
while(+(+i--)!= 0){
     // do 
}
emlai
  • 39,703
  • 9
  • 98
  • 145
Q07
  • 85
  • 2
  • 12

4 Answers4

6

It's called the unary plus operator, and it has (almost) no effect on its argument.

By default, it only promotes its argument to an int. But since in your example i is an int already, +i is effectively a no-op.

Note that it can additionally be overloaded for custom classes in C++ (not in Java or C).

Community
  • 1
  • 1
emlai
  • 39,703
  • 9
  • 98
  • 145
2

The value of the expression +variable is the same as the value of variable. The unary + operator changes neither the value of the expression nor the value of the variable.

R Sahu
  • 200,579
  • 13
  • 144
  • 260
0

Both the + operators are unary operator, used for sign purpose and will not impact any functionality of -- (decrement operator).

Prateek Shukla
  • 583
  • 2
  • 7
  • 26
0

The easiest way to see what it does is to run it and try it out. Using i = 9, it printed 8, 7, 6, 5, 4, 3, 2, 1, 0.

Logically, what it does then is decrements i after performing the i != 0 check, but before the code runs.

This, you will find, is synonymous with while(i-- != 0) which fits the fact that + does not, in fact, affect your code.

Of course, when dealing with multiple operators on a single variable in a single expression you can quite often get undefined code; Code that may run differently on different compilers. For that sake, you probably shouldn't try using anything as confusing as that in your code.

Nonanon
  • 560
  • 3
  • 10