Preincrement
See the example below: in the preincrement, first the variable c
is incremented, and only then assigned to d
:
var c, d;
c=6;
console.log("Pre-incremento\n");
console.log("Numero sem incremento: %d\n", c); // 6
d=++c; // O VALOR É INCREMENTADO, E SÓ DEPOIS PASSADO PARA 'd'
console.log("Valor de 'c':%d\nValor de 'd':%d\n", c, d); // c = 7, d = 7
In this example, c
, which is worth 6 is first incremented and becomes worth 7. Only after that, the variable - which is already worth 7 - is assigned to’d', which is also worth 7.
Post-increment
Note in the example that first the variable is assigned, and only then incremented:
var c, d;
c=6;
console.log("Pos-incremento\n");
console.log("Numero sem incremento: %d\n", c); // 6
d=c++;// O VALOR É PASSADO PARA 'd', E DEPOIS INCREMENTADO
console.log("Valor de 'c':%d\nValor de 'd':%d\n", c, d); // c = 7, d = 6
In this example, c
, which is worth 6 has its value attributed to d
, which is worth 6 also. Only after this operation that c
has its value increased, then worth 7.
The same rule applies to Decrees
Pre-decrement
var c, d;
c=6;
console.log("Pre-decremento");
console.log("Numero sem incremento: %d", c); // 6
d=--c; // O VALOR É DECREMENTADO, E SÓ DEPOIS PASSADO PARA 'd'
console.log("Valor de 'c':%d\nValor de 'd':%d\n", c, d); // c = 5, d = 5
Post-decrement
var c, d;
c=6;
console.log("Pos-decremento");
console.log("Numero sem incremento: %d", c); // 6
d=c--; // O VALOR É PASSADO PARA 'd', E DEPOIS DECREMENTADO
console.log("Valor de 'c':%d\nValor de 'd':%d\n", c, d); // c = 5, d = 6
Therefore
In your pre or post-increment example will always result in same result, as there is no attribution of the value of i
to another variable, you are just returning the value of i
after the increment operation, whether pre or post.
In this way your example works exactly as:
c = 6;
c++; // o valor de 'c' é 7
console.log(c); // retornará 7
or
c = 6;
++c; // o valor de 'c' é 7
console.log(c); // retornará 7
I noticed it’s getting more common to find
++i
in loops than the "classic" post. Does that have a reason? Any personal taste of certain programmers? Maybe aiming for some maintenance? (or maybe it’s just me)– Andre Figueiredo