Thread: How does ++ effect a variable such as var++?

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    4

    How does ++ effect a variable such as var++?

    Hello,

    I'm currently on the loops page of the tutorial on this website and i'm wondering what does the syntax ++ mean at the end of a variable name on the end of a loop.

    // The loop goes while x < 10, and x increases by one every loop
    for ( int x = 0; x < 10; x++ ) {
    How does ++ on the end of the variable name effect the variable or what is this supposed to do? is this also an operator of some sort? "++".

    Cheers Josh.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    x++ in that case is equivalent to x = x + 1.

    In context of being alone, like as you have it in a for loop, ++x and x++ are the same. In context of being used in an expression ++x increments the value of x immediately. x++, on the other hand, increments the value of x, but the original value is used in its place:

    Case in point:

    Code:
    int x = 3;
    std::cout << "x = " << x++ << std::endl;
    Printed value will be 3, however, x itself will be 4.

    Code:
    int x = 3;
    std::cout << "x = " << ++x << std::endl;
    Printed value will match x, which will be 4.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. variable being reset
    By FoodDude in forum C++ Programming
    Replies: 1
    Last Post: 09-15-2005, 12:30 PM
  3. Variable-type variable?
    By Aidman in forum C++ Programming
    Replies: 13
    Last Post: 10-04-2003, 10:03 PM
  4. float/double variable storage and precision
    By cjschw in forum C++ Programming
    Replies: 4
    Last Post: 07-28-2003, 06:23 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM