hey again everyone, what is the difference in c between ++p and p++?
hey again everyone, what is the difference in c between ++p and p++?
In what context? On their own, there isn't any difference that can be measured/noted [in C, in C++ if p is an object, ++p may be faster - but not always].
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
As statements, as matsp noted, pretty much nothing. As expression, the difference is that:
A = p++ is equal to A = p; p++;
and
A = ++p is equal to p++; A = p;
OUTPUT:Code:int a,b; a=10; b=10; printf("%d\n",a++); printf("%d\n",++b);
10
11
A more detailed explanation is that with ++p, the value of p is incremented BEFORE the expression it is part of. with p++, the value of p is incremented AFTER the expression it is part of. With both of them, the value of p is the same both before and after the expression has been evaluated.
A nice article about ++p in for() loops in the FAQ: Cprogramming.com - C/C++ Programming Tips and Tricks
Operating Systems:
- Ubuntu 9.04
- XP
Compiler: gcc
There's no explanation about WHY that makes a difference in a for loop.
EDIT: Just realized this is the C board. Bladactania, there should be no difference in performance in C whether you pre- or post-increment in a for loop. I tend to pre-increment for consistency with my C++ coding, but there's no reason to prefer one over the other.
What "x = p++" does:
That involves two copy constructor calls (one to make the copy, one to return it by value), one assignment operator call (to copy the return value into the result) one destructor call (to destroy the copy during return) and an increment.Code:Make a copy of p Increment p Return the copy by value
What "x = ++p" does:
That involves an increment and an assignment. Period.Code:Increment p Return p by reference
Obviously, these two things have different behavior. But in the context of a for-loop where the only purpose is to increment, obviously the "++p" method is more efficient.
Last edited by brewbuck; 04-23-2009 at 12:37 PM.
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}
I don't understand the need for making a copy of "p" Couldn't it be returned by value then incremented?
How do you increment after you have returned from the function?