Win a copy of Design for the Mind this week in the Design forum!

# post/pre increment operator

O. Ziggy
Ranch Hand
Posts: 430
How does the post and pre increment operator work when used on a for loop? The output of the following example appears to be the same

I was expecting the second loop to start from 1.

Henry Wong
author
Marshal
Posts: 20998
76
O. Ziggy wrote:How does the post and pre increment operator work when used on a for loop? The output of the following example appears to be the same

I was expecting the second loop to start from 1.

Increment operators have a value and an effect. In both cases, the effect is the same -- the variable will be incremented. The value however, are different. With the post increment, the increment happens after, so the value is before the increment. With the pre increment, the value is after the increment.

In your example, you are not using the value -- if is simply thrown away. Hence, there is no difference in your output.

Henry

Ranch Hand
Posts: 72
• 1
The iteration expression is executed after each execution of body

Scotty Mitchell
Ranch Hand
Posts: 46
Suhas Mandrawadkar wrote:The iteration expression is executed after each execution of body

Look at this example and see the output difference now...

Output:
0123456789
12345678910

Ranch Hand
Posts: 72
What you are printing is not iteration expression. You are printing y. Now ++y in a SOP statement will increment it before printing.
Your iteration expression is ++x, and it is still evaluating the body ten number of times

for(initialization and declaration of loop variable; condition expression; iteration expression)
{
//Printing variable x
}

Scotty Mitchell
Ranch Hand
Posts: 46
Suhas Mandrawadkar wrote:What you are printing is not iteration expression. You are printing y. Now ++y in a SOP statement will increment it before printing.
Your iteration expression is ++x, and it is still evaluating the body ten number of times

for(initialization and declaration of loop variable; condition expression; iteration expression)
{
//Printing variable x
}

I was agreeing with you lol..Was showing that in order to get what he wanted he'd need to have the pre increment within the body of the for loop since it executes first.