Thread: difference between ++ and +=1

  1. #16
    Registered User
    Join Date
    Jul 2009
    Posts
    5

    differents

    Quote Originally Posted by karthigayan View Post
    Hi all,
    Can any one tell the difference between the following.

    a++
    a+=1

    Both will do the same operation.I want to know that any one of these have a advantage than the other.
    a++ is a unary operator a+=1 is a binary operator.

    Example:

    unary: a++ it has only one operant.
    binary: a+b it had two operant "a" and "b".

  2. #17
    Registered User
    Join Date
    Oct 2008
    Posts
    84
    I don't know if theres a difference between x++ and x += 1, but there is a difference between the post and pre-increment operators. ++x is actually faster than x++ since the latter requires the original values of x to be stored in a temporary variable and then returned. This is not so much a problem with primitives like int etc since the compiler will optimize it anyway.

  3. #18
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by rocketman03
    ++x is actually faster than x++ since the latter requires the original values of x to be stored in a temporary variable and then returned. This is not so much a problem with primitives like int etc since the compiler will optimize it anyway.
    Note that C does not allow user defined operator overloading.
    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

  4. #19
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    I read a while ago that, for modern x86 processors, "add some_register, 1" is actually faster than "inc some_register". As a result, GCC will never generate the "inc" instruction, at least if you tell it to optimize for any modern processor.

Popular pages Recent additions subscribe to a feed