Thread: incrementing
View Single Post
  #6   Spotlight this post!  
Unread 08-12-2006, 03:39
TimCraig TimCraig is offline
Registered User
AKA: Tim Craig
no team
 
Join Date: Aug 2004
Rookie Year: 2003
Location: San Jose, CA
Posts: 221
TimCraig is a splendid one to beholdTimCraig is a splendid one to beholdTimCraig is a splendid one to beholdTimCraig is a splendid one to beholdTimCraig is a splendid one to beholdTimCraig is a splendid one to beholdTimCraig is a splendid one to behold
Re: incrementing

Quote:
Originally Posted by teh_pwnerer795
Then it will increase by 1..... how do i increase by 2... or maybe 3... would it be?

static int i = 1;

i++2;
i++ and its prefix version ++i only add one. There's no way to increment by a different value using this notation.

To add 2 there are two ways to do it.

The "classic" programming construct
i = i + 2;

and
i += 2;

The second version can be more than just a slightly shorter way of writing the expression if you have a non optimizing compiler or one that doesn't optimize very well.

To digress a little and provide some history, there are three ways to add 1 to a variable.

The increment operator in either postfix or prefix form: i++ or ++i

An in place add: i += 1

And the load, add, and assign: i = i + 1

With a non optimizing compiler and a fairly rich native machine instruction set, these three forms will all generate different machine code and some forms will be more efficient. The programmer would chose the form to use based on knowing how the compiler would translate it.

For instance on an Intel x86 chip the increment operator maps directly to the assembly instruction INC so you do the increment in one instruction.

The second form generates machine code that directly adds the number to the variable. It's longer since it first loads 1 into the accumulator and adds that to the variable directly. Two instructions, so not as efficient.

And finally, the third form causes the processor to load the variable i into the accumulator, add 1 to it, and then store the result back into i's memory location. Even more instructions and slower execution.

On processors like the PICs in the IFI controllers the instruction set is much more limited so it's not as likely to make as much difference. Also, modern optimizing compilers will typically find the "best" machine instructions to use. With some you can even tell them to optimize for smaller code size or faster execution. Sometimes, paradoxically, smaller code is also faster.