+ 1
What is the difference between the add/decrement operator before or after a variable?
An example would be: i++ vs ++i or --i vs i--
6 Answers
+ 4
A simple example:
public class NewMain {
public static void main(String[] args) {
int i = 0;
while (i < 3) {
System.out.println(++i + ". line");
}
System.out.println();
i = 0;
while (i < 3) {
System.out.println(i++ + ". line");
}
}
}
-----------
Output:
1. line
2. line
3. line
0. line
1. line
2. line
+ 3
they are called prefix and postfix variables....
a++ = prefix
++a = postfix
both will give you the same results because in both cases the a is being incremented but it is important when we use a second veriable..
---------------------------
like
a=10;
c = a++;
and after that if i do
printf("%d %d",c,a);
then the..
c will have 10 and
a will be 11
because 1st it assigns the variable into c then it increments the a
------------------------
like
a=10;
c = ++a;
and after that if i do
printf("%d %d",c,a);
then the..
c will have 11 and
a will be 11
+ 2
pre increment adds 1 before operation
post increment adds 1 after operation
pre decrement subtracts 1 before operation
post decrement subtracts 1 after operation
+ 1
operator before a variable means change-then-use value i.e. it changes the value of the variable first then uses it whereas in operator after a variable use-then-change is being implemented..For eg. suppose i=5; then for
{++i
cout<<i;
}
Here output would be 6
whereas for
{i++;
cout<<i;
}
Here output would be 5
Similarly,
{--i;
cout<<i;
}
would show output 4
and;
{i--;
cout<<i;
}
would show output 5 which is assigned value.
0
There are two types of operators in both add/decrement prefix(++x) and postfix(x++). In prefix increase the value before using. In postfix first use the value then increase. In decrement the decrease value