-
March 26th, 2010, 11:45 AM
#1
Increment Operators
I have heard that ++i and i++ are different from each other. I am aware that if I do something like:
int i = 0;
int k = i++;
then k is 0, and if I do
int i = 0;
int k = ++i;
then k is 1. However, I wish to know if there is any difference if I use i in a for loop:
for(int i = 0; i < 10; i++){
cout << i << '\n';
}
If I replace the i++ with ++i, will there be a difference in terms of speed? I have already checked the output and they are the same.
Thanks in advance.
-
March 26th, 2010, 11:50 AM
#2
Re: Increment Operators
There should be no difference. There may be a difference if i was an iterator instead of an integer (or a pointer), which is why we normally prefer the prefix version to the postfix version in such cases.
-
March 26th, 2010, 11:51 AM
#3
Re: Increment Operators
For the primitive types( int, etc ) there won't be any difference (unless the compiler does something funny).
For classes preincrement should run faster as it doesn't need to make copies.
your humble savant
-
March 26th, 2010, 11:56 AM
#4
Re: Increment Operators
What would the difference be if i was an iterator or a pointer? Would it advance the iterator/pointer first, then go through the for loop if it was prefix form?
-
March 26th, 2010, 11:58 AM
#5
Re: Increment Operators
Originally Posted by dietao234
What would the difference be if i was an iterator or a pointer?
An iterator might not be a pointer. It might be an object of a class type for which operator++ was overloaded. In such case, the compiler may not be able to optimise, thus if the postfix version was used, it is likely that it would perform unnecessary copying (which would be necessary if you were actually making use of the return value).
-
March 26th, 2010, 12:01 PM
#6
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|