++ vs +1

This is a discussion on ++ vs +1 within the C Programming forums, part of the General Programming Boards category; What do you think is the best, this: Code: test = (++test) % 10; or this? Code: test = (test ...

  1. #1
    Registered User Drogin's Avatar
    Join Date
    Oct 2005
    Location
    Norway
    Posts
    105

    ++ vs +1

    What do you think is the best, this:
    Code:
    test = (++test) % 10;
    or this?
    Code:
    test = (test +1) % 10;

    It's not good practice to assign values to variables many times in the same expression(in the first example, we set test to be test+1, and we set test to be test+1 %10) . But I guess it's okay here, because the = operator is forcing the computation of (++test) %10, and then the test-variable is set to this value, so that it works as expected.

    But this makes alternative 2 a more clear and nicer code, right?

    EDIT: Changed from test++ to ++test.
    Last edited by Drogin; 11-04-2010 at 04:56 PM.

  2. #2
    Registered User Swarvy's Avatar
    Join Date
    Apr 2008
    Location
    United Kingdom
    Posts
    195
    The two lines of code you posted are not the same.

    The '++' after the number completes the operation (in this case the modulus statement) and then adds one to the value. Whereas the other adds one on and then completes the operation.

    This is the main difference between 'num++' and '++num'.

    Edit: oh, ok, you edited your post nevermind.

    Personally I would say I prefer the '++' notation rather than the '+1' notation, but I can't think of a real programming reason why - That doesn't mean there isn't a reason why one is seen as better than the other, just that I don't know it. Perhaps others would argue '+1' is better. It is possible that it just comes down to programming style and there is no real programming advantage either way.
    Last edited by Swarvy; 11-04-2010 at 05:03 PM.

  3. #3
    Registered User Drogin's Avatar
    Join Date
    Oct 2005
    Location
    Norway
    Posts
    105
    Hehe, sorry about that, it struck me as I was reading my post a second time
    But now it should be correct, so is one of those alternatives in my first post a more correct way than the other?
    Last edited by Drogin; 11-04-2010 at 05:02 PM.

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >But I guess it's okay here
    You guessed wrong, it's still undefined behavior because test is being modified twice between sequence points. That it works as expected for you is irrelevant.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21