0
Incrementing problem in C++
So, I was learning my C++ course, when I found out that it was teaching var++ for incrementing, but some comment was talking about ++var, and I tried it out and didn't get what I expected, why? https://sololearn.com/compiler-playground/cZ43V4rlVwLF/?ref=app
4 Antworten
+ 6
Because Var++ is POST INCREMENT OPERATOR and +++Var is PRE increment operator.
For example :
int var=2;
cout<<var++;
It will print 2 because var++ increases itself AFTER YOU WRITE that cout statement.
That's why it's called 'POST' increment operator.
int var=2;
cout<<++var;
This code will give you 3 because '++var' INCREMENTS itself FIRST before executing cout statement. That's why it's called 'PRE' increment operator
+ 1
Thanks a lot everyone!
Especially Manav Roy , great explanation!
0
Pourquoi ça te surprend ?
Dans ton code sur SoloLearn :
cpp
Copier
Modifier
int x = 5;
cout << x++; // Affiche 5, x devient 6
cout << ++x; // x devient 7, affiche 7
Tu vois donc 5 puis 7, car x++ utilise d’abord 5, puis l’incrémente, ensuite ++x passe à 7 avant d'afficher.
Bonnes pratiques
Dans une boucle :
cpp
Copier
Modifier
for (int i = 0; i < 10; ++i) { ... }
Utilise ++i si tu n’as pas besoin de l’ancienne valeur. C’est plus clair et parfois plus rapide.