Thread: Incrementing styles (x = x++) vs (x +=1) - when to use them

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    8

    Incrementing styles (x = x++) vs (x +=1) - when to use them

    I understand that ++x; is a prefix expression and x++; is a postfix.

    What I can't grasp the concept of is the difference between:

    x = x++; vs. x++;

    Also, while I'm comparison shopping, why use x++; or ++x; as opposed to x = +=1; ?

    If anyone has the time, can you break down the do's and don'ts of:

    x = x++;
    x++;
    x +=1;


    ??

    thanks!
    Last edited by vertigoat; 10-04-2012 at 08:18 AM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by vertigoat
    What I can't grasp the concept of is the difference between:

    x = x++; vs. x++;
    The former results in undefined behaviour; the latter is probably what you wanted to write.

    Quote Originally Posted by vertigoat
    Also, while I'm comparison shopping, why use x++; or ++x; as opposed to x = +=1; ?
    My reasoning is that they are more concise and people are used to them. Otherwise, no big deal. It might even be the case on certain hardware with certain non-optimising compilers that the prefix/postfix operators result in code that is more efficient, but that's generally not a concern.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    don't: x = x++; (undefined behavior)
    do: x++; or ++x; (either one is valid and acceptable)
    do or don't: x += 1; (valid but not as concise as x++)

  4. #4
    Registered User
    Join Date
    Oct 2012
    Posts
    8
    Thank you! Totally understood now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Window styles
    By maxorator in forum Windows Programming
    Replies: 2
    Last Post: 09-09-2006, 09:45 AM
  2. Make C use xp styles?
    By dcboy in forum Windows Programming
    Replies: 1
    Last Post: 04-19-2006, 08:43 AM
  3. EDIT styles
    By krappykoder in forum Windows Programming
    Replies: 4
    Last Post: 03-26-2005, 08:20 PM
  4. Button Styles
    By Malek in forum Windows Programming
    Replies: 2
    Last Post: 06-19-2002, 09:08 PM
  5. listbox styles
    By ll in forum Windows Programming
    Replies: 3
    Last Post: 12-07-2001, 01:39 AM