Page 1 of 1

c++ ++ operator where to put it

Posted: Wed Mar 04, 2009 12:46 pm
by herby490
what is the difference from putting the ++ operator in c++ before and after the variable like
n++ or ++n
I know there is a difference but I don't know what it is and the books i have read don't explain it well

Re: c++ ++ operator where to put it

Posted: Wed Mar 04, 2009 12:59 pm
by avansc
first off google is great... and wont give you snotty startups like this.

anyways.

try something like this.

Code: Select all

int a = 10;
printf("%d\n", a++);
printf("%d\n", a);

int b = 10;
printf("%d\n", ++b);
printf("%d\n", b);
that should make things abundantly clear.

Re: c++ ++ operator where to put it

Posted: Wed Mar 04, 2009 1:01 pm
by programmerinprogress
Postfix ++ allows you to use a statement where you can take the previous value, and then increment it afterwards
Prefix increments the variable first, thus giving the variable your assigning it to, the incremented value.
e.g.

Code: Select all


int a = 0;
int b = 5; 

a = b++; // a will equal 5, b will equal 6

a = 0; 
b = 5; 

a = ++b ; // a will equal 6, b will equal 6

Re: c++ ++ operator where to put it

Posted: Wed Mar 04, 2009 8:04 pm
by MarauderIIC
Also if the statement is only "i++" or "++i", such as in a for loop, consider using ++i. It's faster on non-built-in types (non-built-in as in, not a string or an int or anything else that highlights automatically), because i++ makes a copy.

Re: c++ ++ operator where to put it

Posted: Fri Mar 06, 2009 3:00 am
by ansatsusha_gouki
I got confused with the whole post and prefix operator myself :roll:

Re: c++ ++ operator where to put it

Posted: Fri Mar 06, 2009 3:51 pm
by MarauderIIC
In general, prefix does the increment as the first thing in the statement, and postfix does the increment as the last thing in the statement.
But run avansc's sample code.