Can someone please explain to me the difference between ++i and i++ when written as part of an expression (i.e. within loops and if statements) ? Thanks :)

## All 36 Replies

Can someone please explain to me the difference between ++i and i++ when written as part of an expression (i.e. within loops and if statements) ? Thanks :)

//Lets declare i, and set it equal to 4.
int i = 4;

//Now say their is a function nammed goFetch(int), and we wanted to pass an increment of i to it

//i = 4 before this code gets touched, the value 4 would be passed, and then i would become 5
goFetch(i++);

//i = 4 before this code gets touched, i gets incrimented before anything else (and becomes 5), and the value 5 would be passed
goFetch(++i);

So, ++i means to incriment first then give the incrimented value, and i++ means to give the original value, then incriment.

LOOPS
for (int i = 0; i < 10; i++)
- vs -
for (int i = 0; i < 10; ++i)

no effective difference.

for (int i = 0; ++i < 10; )
- vs -
for (int i = 0; i++ < 10; )

Here, the first one will loop 9 times (1..9), the second one 10 (0..9). In both, the value of i in the body of the loop will be 1-based rather than 0 based.

IF/WHILE
if (i++ < 10)
while (i++ < 10)
- vs -
if (++i < 10)
while (++i < 10)

The second set will execute one less than the first set, same as the for ().

This is 'undefined' and tends to work differently on different compilers, and differently between optimized and non-optimized builds:

int i = j++ + j++;
int i = ++j + j++;

and the like. And though this might sound silly, consider this:

``````#define MAX(x,y) ((x > y) ? x : y)

int i = 10;
int j = 11;
int k = MAX(i,++j); // j gets incremented multiple times!``````

That's a big advantage of small inlined functions vs #defines; the lack of those side effects:

``````inline int MAX(int x, int y) { return ((x > y) ? x : y); }

int i = 10;
int j = 11;
int k = MAX(i++,j); // k will be 11``````

It`s simple :)

``````int i;
i++;    //Postfix
++i;    //Prefix``````

if you still dont get it just cout << and it will all become clear

hi all. .

``````for ( int i =0; i >10; i++; )
{	do something	}``````

here i will be 0 in the first time code run .. thats mean the code will be done 10 times

``````for ( int i =0; i >10; ++1; )
{ ` do something	}``````

here i will be before the program done the first time .. thats mean the code will be done 9 times

huh? First just a nit: it should be i < 10, not i > 10, or else the loop won't execute at all. Second, the i++/++i (another nit: you said ++1) is done at the BOTTOM of the loop, after the code in the braces, so ++i and i++ won't affect the loop either way.

Or am I sniffing too many whiteboard pens again?

yaeh i am sorry for this mistake i really i was tired when i wrote this reply but i am soorry again .. :(

``````#include <iostream> // This line of code is necessary to include all the C++ standard functions\classes definitions

using namespace std; // Set our namespace to standard (don't stress on this right now)

void main() // This creates our function main()

{ // Beginning of the program

int min=0, max=0, i=0; // We initialize 3 integer (number) variables to store

// Our range. We set them equal to zero or else they

// Will be some crazy number like -858993460. We could

// Also have said:

// int min=0;

// int max=0;

// int i=0;

// They are the same thing, it is just cleaner the other way

// Now we prompt the user to input a number for the min

cout << "Input your first number to count from: ";

// Then we wait until they press <enter> and read what they typed in

cin >> min; // We store the number they type in in the variable "min"

// Now we prompt the user to input a number for the max

cout << "Input your last number to count to: ";

// Then read in the maximum number to count to and store it in the variable "max"

cin >> max; // Now we have the maximum number they want to count to store

// Now here comes the loop:

// This is called a "For Loop". You will use these a million times.

// Ok, here is what it does. It gets a starting point

// "i=min" "i" is used as a counter

// "i" now equals min, let's say we typed in 10.

// This is the same thing as saying "i=10", but we don't

// Know WHAT the number is so we hold it in a variable: min

// "i <= max" This says, keep looping until this condition is false.

// In this case, "Keep looping until i is greater than max."

// Let's pretend that max is 15. The loop will quit when i = 16 or over

// You might be thinking, why would i = 16 or over? "i" equals "min" (let's say 10)

// Well, the next parameter passed into the "for" loop is where we say what happens to "i"

// "i++" This tells the compiler to add 1 to "i" each time through

// This is the same thing as saying : "i = i + 1", It's just shorthand

// for(start, condition for the loop, after we go through the loop each time - do this) )

// You'll also notice we don't have a ";" after the "for" loop...

// Good "i"! :) if we put a semicolon after this, the loop would never run.

for(i=min; i <= max; i++) // That is because a ";" says we are done with the line, we ARENT... We never put a ";" after anything with a "{" after it .. look at "void main()" ..

{ // We have a "{" to say everything after "{" is in the loop

cout << i << endl; // Here we print out i each time through the loop and go to the next line

} // Everything after "}" is out of the loop, if the loop is not finished, go back to the top

// You might be wondering what this does? If so.. let's go through the loop:

// Let's stick to our previous example of min=10 and max=15

// for(i=10, 10 <= 16, 10 + 1 (only if middle condition is not met, so i still = 10) )

// {

// cout << i << endl;

// }

// That is one time through the loop, when it hits "}" .. The loop executes the 3rd parameter:

// Which happens to be "i++". Now, i = 11 right? we just added 1 to i which was 10.

// The compiler never goes back to the first parameter which was "i=min". That was just to start "i" off.

// So, after the first loop, and we add 1 to "i", the compiler goes and check the middle condition

// To see if the loop should continue.. So:

// "11 <= 16" It's still TRUE, so we go through the loop again.

// Now we print out 11, then 12 <=16, then print 12, etc...

// Until we print out "16" , after the loop ends, 16 gets 1 added to it. i = 17

// "17 <= 16" This is FALSE, so the loop quits and the code

// Goes past the loop and past the "}". Since there is nothing else in the program, the program is over.

} // We end "main()" ending our program

// We just completed our first for loop. Pretending we typed in 10 and 15, here is the output:

// Input your first number to count from: <we type in 10 and press ENTER>

// Input your last number to count to: <we type in 15 and press ENTER>

// 10

// 11

// 12

// 13

// 14

// 15

// Press any key to continue``````

read this tutorial carefully u will get it ..

Can someone please explain to me the difference between ++i and i++ when written as part of an expression (i.e. within loops and if statements) ? Thanks :)

i++: do the calculation or do the comparison before the i's value is increment.
++i: increment the i's current value by 1 before doing the calculation or doing the comparison.

Hence, using in for loop, we cannot see clearly the differences.
However, using in if statement, they are clearly different.

For instance, we have i = 4.
if (i++ == 4) // the result is true since the current value of i is 4. After doing the comparison, then the i's value now becomes 5.

Whereas, if (++i == 4) // the result is false since the value of i is increment first, now the value of i becomes 5, then it does the comparison.

that is simple
++i means pre increment.
i++ means post increment.
consider the programme

``````main()
{
int a=7;
printf("%d\t%d\t%d\t%d\t",++a,a++,++a,a++);
printf("%d\n"a);
getch();
}
``````

the output is

``````10        10        8      8
11
``````

a++ here increments the value and shows it but ++a increments the value and gives it for next operation.ie ++a increments but not show the value.

if you are using void main()function at the beginning do not use return 0 at the end.

if you use int main()function at the startup use return 0 at the the end..

#include<iostream.h>
int main()
{
int x=5;
cout<<x<<endl; //print 5
cout<<x++<<endl;// the 5 is print first .then the 1 is added
cout<<x<<endl;//the x get 6 becoz 1 is been added
}
----------------------------------
2 program-
#include<iostream.h>
int main()
{
int x=5;
cout<<x<<endl; //print 5
cout<<x<<endl; //the variable now is 6
return 0;
}

You picked the worst example you could -- it is purely undefined behavior. See http://www.eskimo.com/~scs/C-faq/q3.2.html

If you are using `void main()`, and are on a hosted implementation, you are incorrect. (It seems to me I may have mentioned this already?)

Can someone please explain to me the difference between ++i and i++ when written as part of an expression (i.e. within loops and if statements) ? Thanks :)

Could I suggest a book?: C++ Primer 3rd Edition

Covers tiny stuff like performance details and the new C++ standard very well,bit advanced but very good if you want details.

Postfix(p++) and Perfix(++p).

Rules
p++ - First use value then increment.
++p - First increment then use value.

If you still dint understand after all the stuff the other guys gave.Then check this out.

You are mad at a guy, he shouts at you,making you madder.With p++ you shout at the guy then slap him and with ++p you slap him first, then shout at him.

The end result is that on the first case he would have got a piece of your mind before getting the physical part for what ever he did, and the other way around with the second.
Which method you want to use depends on the situation and your choice.

(Hint: p++, if you plan on running)

;),no offense anyone.

Also,val++ (real c++ here ok) is what is commonly used by many programmers.

As far as loops go it depends on which type of loop you re going to use like
for(), while() , and do while() ,where it's declared and where the expression is placed.Just apply the rules and you will have the result.

Can someone please explain to me the difference between ++i and i++ when written as part of an expression (i.e. within loops and if statements) ? Thanks :)

Simply ++i increments i first and then does any computation in the loop ...
and i++ first does the computation and then increments i.

try this:

//---------------------------------
// try_i.cpp
#include <iostream.h>

void main()
{
int i = 1;
int last_value;

last_value = i++;
cout << "i++ = " << i << endl;

last_value = ++i;
cout << "++i = " << i << endl;

cout << "Again:" << endl;
cout << "i++ = " << i++ << endl;
cout << "++i = " << ++i << endl;
}

Can someone please explain to me the difference between ++i and i++ when written as part of an expression (i.e. within loops and if statements) ? Thanks :)

The functionality of both the syntexes are same but difference lies in preference of operators.
++i means first increement and then process the instruction
i++ means first process the instruction and then increment.
:cool:

practical is the key to understand the concept in a better way.

One thing that is good to remember is that ++i is returned by reference while i++ is returned by value.

You should use ++i to increment where the old value of i is not needed.

One thing that is good to remember is that ++i is returned by reference while i++ is returned by value.

Never heard that one before.:-O

//Lets declare i, and set it equal to 4.
int i = 4;

//Now say their is a function nammed goFetch(int), and we wanted to pass an increment of i to it

//i = 4 before this code gets touched, the value 4 would be passed, and then i would become 5
goFetch(i++);

//i = 4 before this code gets touched, i gets incrimented before anything else (and becomes 5), and the value 5 would be passed
goFetch(++i);

So, ++i means to incriment first then give the incrimented value, and i++ means to give the original value, then incriment.

Hi,

As i++ is used in a statement, then the valude of i in the statement, remains same ie unincremented. But after the statement, this is incremented.

When ++i, is used then it is incremented with in the statement it self.

bye

hi
when inside a loop for example
for(i=0;i<10;i++);
here the loop starts from 0,
and in the case of ++i;
the loop starts from 1,
in the former the assignment is before increment
in the later the assignment is after i gets incremented

>>and in the case of ++i;
>>the loop starts from 1,

No it doesn't -- the loop still starts with 0 because the i is not incremented until after the iteration of that loop finishes.

i++ first takes the value of i and then gives the increment----(POST INCREMENT OPERATOR) whereas ++i first gives the increment to the assigned i value---(PRE INCREMENT OPERATOR)

example::: i=6

i++ takes i and then gives increment i.e.,i++=5 but the compiler stores the value as 6 which is not the displayed output

++i gives increment first i.e., ++i=6...

``````void main()
{
int i,x,y;
printf("enter an int:");
scanf("%d",&i);
x=i++;
y=++i;
printf("%d\n%d",x,y);
getch();
}``````

input: enter an int:5
output:5
7

HERE THE VALUE OF ++i IS 7 COZ THE COMPILER STORES THE VALUE OF i++ AS 6...

WTF.. All she asked was the difference between ++i and i++, not such weird details. Can't you just say that, ++i will first increment the value of i and then assign it., while i++ will first assign the value and then increments (so the variable assigned before gets to keep the old value of i).

WTF.. All she asked was the difference between ++i and i++, not such weird details.

I agree (beating a dead horse)-- but everyone has to get in his/here 2 cents worth :)

xDD Totally, kekeke.. Wonder what they'll throw at us if we ask the difference between a long int and a short int. kekeke

Don't mean to hijack this thread, but yes there may be a difference, but then again there might not be one also. depends on the compiler, which I'm sure you already know but other readers may not.

Hehe, xD

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.