Thread: newbie needs help with lesson 3: loops

  1. #1

    newbie needs help with lesson 3: loops

    in lesson 3 where says x++ in the example, what does the ++ bit do to x?

  2. #2
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    x++ means increment x. If x is 5, the result of x++ is 6.
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  3. #3
    Registered User
    Join Date
    May 2003


    it increments!

    suppose we have a variable " Length "


    is just like writing

    Length = Length + 1

    increment means adding 1 to the variable, so if

    Length = 25

    then we type


    then the value of Length is now 26
    I have a code which stops life!

  4. #4
    Registered User HaLCy0n's Avatar
    Join Date
    Mar 2003
    Another shorthand way of doing this is to say:


    It'll take the current value of length and add whatever you specify to it. Just make sure before you use any of these methods that length is initialized.

  5. #5
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Also legal is ++length. It does the same thing. The only difference is that the value ++length returns is after it increments length, which length++ just returns length.

  6. #6
    Registered User
    Join Date
    May 2003
    Here's some example code to help you out:

    int x = 5;
    x++; // Line A
    // x is now 6  
    ++x; // Line B
    // x is now 7
    int y = x++; // Line C
    // x is 8, y is 7 (the OLD value of x).
    int z = ++x; //Line D
    // x is 9, z is 9 (the NEW value of x).
    If your code does not need the return value, use ++x not x++.
    I.e. instead of Line A's syntax, use Line B's.

    The reason? ++x is always at least as efficient as x++ and sometimes more efficient. The reason is that x++ has to return an old, temporary value. In certain cases, the compiler can optimize away the unused temporary, but not always.

    So, as a rule, if either will work, use ++x not x++, it's a better habit to be in.

    So, write your for loops like:

    for (int x = 0; x < 10; ++x)

    which looks a little unusual but is a better habit to be in.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Lesson 3: Loops
    By The SharK in forum C++ Programming
    Replies: 3
    Last Post: 09-06-2006, 11:01 AM
  2. Newbie in problem with looping
    By nrain in forum C Programming
    Replies: 6
    Last Post: 11-05-2005, 12:53 PM
  3. help with arrays and loops
    By jdiazj1 in forum C Programming
    Replies: 4
    Last Post: 11-24-2001, 04:28 PM
  4. for loops - newbie q's
    By Narciss in forum C Programming
    Replies: 8
    Last Post: 09-26-2001, 02:44 AM