[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppIncrementOperator
Its opposite operator is the decrement operator, --.
Prefer ++i to i++ [1].
There are four ways to increment a value by 1:
When you define these 4 ways in a class then ways #1 and #3 produce a temporal copy of it, which might slow down your program unnecessarily. Therefore, #4 will be quicker of equally fast as #3.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppIncrementOperator
(C++) ++ operator
The increment operator is used to raise an int's value by one.Its opposite operator is the decrement operator, --.
int i = 0; ++i; assert(i==1);
- include <cassert>
Prefer ++i to i++ [1].
There are four ways to increment a value by 1:
1) i = i + 1; 2) i += 1; 3) ++i; 4) i++;
When you define these 4 ways in a class then ways #1 and #3 produce a temporal copy of it, which might slow down your program unnecessarily. Therefore, #4 will be quicker of equally fast as #3.
Overloading the increment operator
struct MyInt
{
//Prefix
MyInt& operator++()
{
++mX; //Increment
return *this; //Return class reference
}
//Postfix
MyInt operator++(int)
{
MyInt old(*this); //Copy
++(*this); //Increment original using prefix
return old; //Return old copy
}
int mX;
};
int main()
{
MyInt m;
++m;
m++;
}
'Increment operator' links
Reference
- Bjarne Stroustrup. The C++ Programming Language. 2000. 3rd edition: ISBN: 0-201-88954-4. 2000. Item 19.5.7: 'Prefer ++p to p++'
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
