Increment and decrement confuses me plz | Sololearn: Learn to code for FREE!


Increment and decrement confuses me plz

#include <iostream> using namespace std; int main() { int x=5; int p=5; int y=x+--x; int q=p+++p; cout<<y<<" "<<q; return 0; } output: 8 11 expected : 8 12 or 9 11

3/6/2017 4:50:49 AM

manoj katari

4 Answers

New Answer


int q = p+++p is ambiguous and is interpreted differently by different compilers.


in general words: Increment: you add something to your variable (e.g: p++) decrement: you subtract something of it (e.g: p--)


'+' operator and prefix/postfix operator have the same precedence. Which means that none of them come first or come last when processing them. Its like 3+4+5. You can add 4 and 5 first. Or you can add 3 and 4 first. In this case, we call this "Undefined Behaviour". Where the compiler may give different possible results.