Krazy: prefix vs. postfix ++ and -- operators

Matthew Dawson matthew at
Tue Jan 11 15:44:28 GMT 2011

On Tuesday 11 January 2011 10:16:23 Christoph Feck wrote:
> Krazy says:
> "You should use ++ and -- as prefix whenever possible as these are more 
> efficient than postfix operators. Prefix increments first and then uses the 
> variable, postfix uses the actual; the variable is incremented as well. 
> Because of this, the prefix operators are inherently more efficient."
> Considering that today's CPUs have multiple pipelines, using a value directly 
> seems faster to me than waiting for it to be incremented or decremented.
> Is this krazy warning still correct?
> Christoph Feck (kdepepo)

(This all applies equally to the -- operator, it is omitted for clarity.)

I'm assuming this Krazy warning is for incrementing a variable in a for loop as opposed to incrementing and assigning the variable.  Prefix is generally considered faster as it avoids an unnecessary copy of the data.  Effectively, the prefix increment operator looks like:
int &operator++(){ //Prefix
	number = number+1;
	return number;

Verus postfix looks like:
int operator++(int){
	int temp = number;
	number = number+1;
	return temp;

When executing a for loop, using the postfix operator incurs that copy and thus can slow down the code.  This would be especially more relevant with iterators or the like as the compiler would have a harder time optimizing out the copy.

However when using the ++ operator in assignment, like:
int num2 = num1++;
int num3 = ++num1;

Both lines will have different results in num2 and num3 (num2 != num3) and the appropriate operator should be used.  So postfix doesn't use the value directly.  In fact the prefix uses the value directly.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: This is a digitally signed message part.
URL: <>

More information about the kde-core-devel mailing list