[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppDecrementOperator
Its opposite operator is the increment operator, ++.
Prefer --i to i-- [1].
There are four ways to decrement 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]
CppDecrementOperator
(C++) -- operator
The decrement operator is used to lower an int's value by one.Its opposite operator is the increment operator, ++.
int i = 1; --i; assert(i==0);
- include <cassert>
Prefer --i to i-- [1].
There are four ways to decrement 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 decrement 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--;
}
'Decrement operator' links
Reference
- Bjarne Stroustrup. The C++ Programming Language. 2000. 3rd edition: ISBN: 0-201-88954-4. 2000. Item 19.5.7
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
