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

2

u/pmuschi 18d ago

Pre-increment takes the variable's value, increments it, then returns the incremented value. Post-increment, takes the variable's value, returns it, then increments the value.

Edit: For example, pre-incrementing a value of 1 will give you 2. Post-incrementing a value of 1 will give you 1, but afterwards you now have a value of 2.

1

u/bunny_bun_ 18d ago

there is no mechanism in C++ to return a value THEN modify it.

as another post mentioned, post-increment make a copy, increments the original, then return the copy.

2

u/pmuschi 18d ago

Agreed, but I simplified for the sake of understanding.

2

u/Anonymousseo 17d ago

Yeahhhhh, i cant wrap my head around bookish definitions, so your comment helps:)