Thread: newbie needs help with lesson 3: loops

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. x++ means increment x. If x is 5, the result of x++ is 6.

3. HAHA

it increments!

suppose we have a variable " Length "

Length++

is just like writing

Length = Length + 1

increment means adding 1 to the variable, so if

Length = 25

then we type

Length++

then the value of Length is now 26

4. Another shorthand way of doing this is to say:

Length+=1;

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. 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. Here's some example code to help you out:

Code:
```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