New course! Every coder should learn Generative AI!
Try a free lesson+ 1
what is the difference between a++ and ++a?
3 Answers
+ 6
++a is prefix which increases the variables value and the uses the new value in expression.
a++ is posfix which takes the variable value first in the expression and then increase the variable.
E.g. prefix:
int x = 4;
int y = ++x; // y = 5
prosfix:
int x = 4;
int y = x++;// y = 4
+ 1
Example with arrays;
int numbers[3] = {7, 9, 1};
int i = 0;
cout << numbers[i++] << endl;
// Outputs 7 and now i = 1;
cout << numbers[++i] << endl;
//Outputs 1 and now i = 2;
When postincrementing(i++), i was used as an index of the array and THEN incremented by one.
When preinctementing(++i), i was incremented by one and then used as an index of array.
0
a++ postponed increment and ++a is prepond increment