Hey.

What's better, i++ or ++i? Well ++i returns the value after it's incremented, but which is faster? (not necessarily for int, user-defined types with operator++ overloaded too.)

Dani AI

Generated

Short answer: for built-in types (ints, pointers) there is no practical speed difference on modern compilers; for user-defined types (iterators, classes) prefer prefix ++i unless you need the previous value because postfix i++ normally makes a copy.

Good pointer from — the why is simple. Prefix operator++() usually increments in-place and returns a reference; postfix operator++(int) returns the old value by value, so a temporary copy is created. A common, correct implementation pattern for a class is:

MyType& operator++() { /* increment *this */ return *this; }

MyType operator++(int) { MyType tmp(*this); ++(*this); return tmp; }

That copy is what can make i++ heavier for non-trivial types. C++11/14/17 optimizations (move constructors, copy elision/RVO) reduce the cost in many cases, but the copy can still exist or be logically present, so the rule of thumb stands: use ++i for loops and incremental operations on iterators/objects when you do not need the old value.

Practical guidance for : use whichever reads clearer for built-ins; for templates/generic code, prefer prefix (or document the needed semantics) to avoid surprising instantiations with expensive copies. Also keep increments simple and avoid combining modifications of the same object in complex expressions — separate statements are clearer and safer.

Further reading: C++ increment/decrement operator rules and typical overload patterns are documented on cppreference (see the operator++/operator-- page) and copy-elision behavior is covered on cppreference as well.

Recommended Answers

All 2 Replies

Thanks, Duoas.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.