[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppDecrementOperator

(C++) -- operator

The decrement operator is used to lower an int's value by one.

Its opposite operator is the increment operator, ++.

  1. include <cassert>
int i = 1; --i; assert(i==0);


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


last edited (November 11, 2006) by bilderbikkel, Number of views: 1354, Current Rev: 4 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.