Incriment and Decriments

This is a discussion on Incriment and Decriments within the C++ Programming forums, part of the General Programming Boards category; I'm having trouble figuring out whats the difference of using them prefix and postfix. What times would I need to ...

  1. #1
    Registered User
    Join Date
    Aug 2006
    Posts
    15

    Incriment and Decriments

    I'm having trouble figuring out whats the difference of using them prefix and postfix.
    What times would I need to use both of those operations?

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,075
    Quote Originally Posted by Syllable
    I'm having trouble figuring out whats the difference of using them prefix and postfix.
    Simple. The prefix increment/decrement operators return the incremented/decremented value, while the postfix returns the original value. That is to say
    Code:
    int x = 5;
    
    std::cout << x++; // Will output '5'
    Code:
    int x = 5;
    
    std::cout << ++x; // Will output '6'
    It's generally better to use the prefix, as it takes less time to resolve (it doesn't have to store the original value temporarily), unless the situation arises where you need the pre-updated value to resolve in the next operator. For instance, in the subscript operator.
    Code:
    while(x < 10)
       std::cout << arry[x++];
    Last edited by SlyMaelstrom; 09-03-2006 at 10:53 PM. Reason: Some gramatical adjustments
    Sent from my iPadŽ

  3. #3
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Oh, and to the OP, one thing you should learn never to do with increments:

    Code:
    int x = 5;
    
    std::cout << x++ << " " << ++x; // Will output whatever the heck it feels like (the behavior is undefined).
    That is, you can't have two things which both modify the same value in a single expression. Incrementing is a common cause (although function calls can do it too).
    Last edited by Cat; 09-04-2006 at 03:06 AM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  4. #4
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    What Cat mentioned is a quirk of sequence points.
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

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