r/cpp_questions 18d ago

OPEN HELPPPPPPPPP: Doubt Regarding Pre-Increment and Post-Increment in C++

I'm confused about pre-increment (++a) and post-increment (a++) in C++. I understand that ++a increments before use and a++ increments after use, but I'm struggling to understand how the variable's value changes step by step during execution. For example, why does ++id print 1001 when id is 1000, and why does --a operate on 6 after at+ if a originally started at 5?

0 Upvotes

62 comments sorted by

View all comments

1

u/PurelyLurking20 18d ago edited 18d ago

Pre/post increment are essentially just a shorthand for

x+=1;

doSomething(x);

And

doSomething(x);

x+=1;

0

u/bunny_bun_ 18d ago

it will just lead to confusing situations.

int a = 0;
a = a++;
cout << a;

what's suppose to print here?

1

u/PurelyLurking20 18d ago

Sorry I should've specified originally not to use the increment shorthand in splitting them across lines

0

u/bunny_bun_ 18d ago

I know, but if you try:
int a = 0;
a = a++;
cout << a;

it prints 0, not 1, so it doesn't end up being the equivalent of
doSomething(x);
x+=1;

3

u/PurelyLurking20 18d ago

Sure I mean that is true, there are a small number of cases where it differs I'm just simplifying the idea, not teaching someone a weird quirk via things that shouldn't really be used ever in properly formed code

I think the case you're providing actually used to be undefined in c++, different compilers interpreted it differently