CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Mar 2010
    Posts
    13

    Increment Operators

    I have heard that ++i and i++ are different from each other. I am aware that if I do something like:

    int i = 0;
    int k = i++;

    then k is 0, and if I do

    int i = 0;
    int k = ++i;

    then k is 1. However, I wish to know if there is any difference if I use i in a for loop:

    for(int i = 0; i < 10; i++){
    cout << i << '\n';
    }
    If I replace the i++ with ++i, will there be a difference in terms of speed? I have already checked the output and they are the same.

    Thanks in advance.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Increment Operators

    There should be no difference. There may be a difference if i was an iterator instead of an integer (or a pointer), which is why we normally prefer the prefix version to the postfix version in such cases.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Mar 2002
    Location
    Kent, United Kingdom
    Posts
    399

    Re: Increment Operators

    For the primitive types( int, etc ) there won't be any difference (unless the compiler does something funny).

    For classes preincrement should run faster as it doesn't need to make copies.
    your humble savant

  4. #4
    Join Date
    Mar 2010
    Posts
    13

    Re: Increment Operators

    What would the difference be if i was an iterator or a pointer? Would it advance the iterator/pointer first, then go through the for loop if it was prefix form?

  5. #5
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Increment Operators

    Quote Originally Posted by dietao234
    What would the difference be if i was an iterator or a pointer?
    An iterator might not be a pointer. It might be an object of a class type for which operator++ was overloaded. In such case, the compiler may not be able to optimise, thus if the postfix version was used, it is likely that it would perform unnecessary copying (which would be necessary if you were actually making use of the return value).
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  6. #6
    Join Date
    Mar 2010
    Posts
    13

    Re: Increment Operators

    Thank you very much

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