1

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

int i=0;
while(+(+i--)!= 0){
     // do 
}
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
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
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
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
  • 204,454
  • 14
  • 159
  • 270
0

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

Prateek Shukla
  • 593
  • 2
  • 7
  • 27
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