How does +variable
operate or +(+variable)
operate?
int i=0;
while(+(+i--)!= 0){
// do
}
How does +variable
operate or +(+variable)
operate?
int i=0;
while(+(+i--)!= 0){
// do
}
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).
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.
Both the + operators are unary operator, used for sign purpose and will not impact any functionality of -- (decrement operator).
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.