c++ Very important | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

c++ Very important

int z = 10; cout << ++z << z << z++ << z<<"\n"; why?result different.

28th Oct 2017, 1:33 PM
Mansour akhtyarzadeh
Mansour akhtyarzadeh - avatar
2 Answers
+ 20
The order in which your z++ and ++z statements are evaluated is undefined, so is the effect of your code. Discussion : [https://stackoverflow.com/questions/33445796/increment-and-decrement-with-cout-in-c] Avoid doing the incremental/decremental operation "in a row" inside the cout. That causes undefined behavior. Example: Compare two groups together. They both do the same operation but as you clearly see, former expresion's behavior is completely undefiend. #include <iostream> using namespace std; int main() { int x = 1; int y = 2; cout << x++ << " " << ++x << " " << --y << " " << y++ << "\n\n"; x = 1; y = 2; cout << x++ << endl; cout << ++x << endl; cout << --y << endl; cout << y++ << endl; } Output: 2 3 2 2 1 3 1 1 Live link : [http://cpp.sh/8xuaw]
28th Oct 2017, 1:40 PM
Babak
Babak - avatar
+ 16
28th Oct 2017, 1:41 PM
Hatsy Rei
Hatsy Rei - avatar