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

(C++) ++ operator

The increment operator is used to raise an int's value by one.

Its opposite operator is the decrement operator, --.

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


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++'


last edited (November 9, 2006) by bilderbikkel, Number of views: 2102, Current Rev: 8 (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.