CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Threaded View

  1. #1
    Join Date
    Aug 2002
    Location
    Madrid
    Posts
    4,588

    C++ Operator: Why should I use '++i' instead of 'i++'?

    Q: Someone told me that if I want to increment a variable and that's all, I should use ++x instead of x++. Is this true?

    A: If incrementing is all that you want to do (you are not assigning the variable to something else), then yes this is a good practice, especially if you are using the increment operator on a class.

    Code:
    // Prefix operators are preferred in cases in the following common cases:
    
    for (;checkstate(x);++x) dosomething(x);
    
    ++x;
    For the standard data types there is usually no performance difference, but for classes there are! The reason is that (for most common implementations of) postfix operators retain a temporary copy of original variable and because the return value is returned by value, not by reference. The following code exemplifies this:

    Code:
    class MyClass
    {
    public:
        MyClass& operator++()    //Prefix increment operator  (++x)
        {
            //Perform increment operation
            return *this;
        }
    
        MyClass  operator++(int) //Postfix increment operator (x++)
        {
            MyClass temp = *this;
            //Perform increment operation
            return temp;
        }
    };
    FAQ contributed by: [Kevin Hall]


    Last edited by Andreas Masur; July 24th, 2005 at 04:37 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured