C/C++中++i、i=i+1与i+=1是否完全等价?
++i;, i = i + 1;, and i += 1; Fully Equivalent? Great question! Let’s break this down across the dimensions you mentioned—since you already clarified we’re focusing on the prefix increment (++i, not postfix i++), we can dive straight into the comparisons:
1. Semantics & Syntax
For built-in types (like int, long, float, etc.), all three statements are semantically identical: they all increment the value of i by 1 immediately within the statement. Syntax-wise, they’re just different ways to write the same core operation.
The catch comes with user-defined types (e.g., a custom BigInteger class with overloaded operators):
i = i + 1first callsoperator+to create a temporary object (the result ofi + 1), then assigns that temporary back toiviaoperator=.i += 1callsoperator+=, which modifies the existingiobject directly—no temporary is created.++icallsoperator++()(the prefix increment operator), which also modifiesidirectly, typically with no temporary object.
In this case, i = i + 1 has a distinct semantic flow compared to the other two, even if the end result matches.
2. Performance
Again, the split is between built-in and custom types:
- Built-in types: Modern compilers (GCC, Clang, MSVC, etc.) optimize all three statements to identical machine code. You won’t see any performance difference—they’re effectively the same under the hood.
- Custom types:
i = i + 1is slower because of the temporary object’s construction and destruction overhead.++iandi += 1avoid this extra work, making them more efficient for complex types.
3. Memory Management
- Built-in types: All three operations only touch the memory allocated for
iitself. No extra memory is allocated, so there’s no difference here. - Custom types:
i = i + 1requires memory for the temporary object created byi + 1.++iandi += 1modifyiin-place, so no additional memory is needed.
Final Takeaway
If you’re working with standard built-in numeric types, these three statements are functionally interchangeable—compilers will erase any syntactic differences. For user-defined types with operator overloading, stick to ++i or i += 1 if you want to avoid unnecessary temporary objects and improve efficiency.
内容的提问来源于stack exchange,提问作者RobertS supports Monica Cellio

