i ++ (prefix formula increment) and ++ i (postfix increment) of the difference between the efficiency ratio -C / C ++ program basis (c)

Case explain

#include<iostream>
#include <stdio.h>

int main()
{
	int i = 10;
	printf("%d\n", ++i);
	printf("-----------------\n");

	i = 10;
	printf("%d\n", --i);
	printf("-----------------\n");

	i = 10;
	printf("%d\n", i++);
	printf("-----------------\n");

	i = 10;
	printf("%d\n", i--);
	printf("-----------------\n");

	i = 10;
	printf("%d\n", -i++);
	printf("-----------------\n");

	i = 10;
	printf("%d\n", -i++);
	printf("-----------------\n");

	system("pause");
	return 0;
}

operation result: 

After analysis, this problem is very simple, as long as the pre-Gaga (or minus minus), are the first to complete the self-increase (decrease) operation, then the next step ( printf print is the next step in this case inside ); as long as the post is jerk (Save or Save), the next step is to complete, then the self-increase (decrease) operation; the next step without waiting for that front and rear on the same !

So, here again consider a problem, higher ++ i and i ++ that efficient?

May be seen by the above example, if the increment of the result of the arithmetic expression, is not used, but only two simple operation for increasing a number, then the effect prefix and postfix method is the same method, and then consider carefully, the data type of the object if the operation is a common type int or a built-in data types in general, that efficiency is not entirely bad.

However, if the execution of i ++, i in (especially if i was a kind of thing) is a defined data type it yourself? Prefix formula (++ i) to return a reference to the object, and postfix (i ++) must return the value of the object, it will have a greater replication overhead, causing reduced efficiency, therefore, result in a return prefix style references, certainly higher efficiency more. Accordingly, in processing data from the independent variable type defined, to make use of more efficient formulas prefix!

Added: What is the built-in data types? A: Generally refers to the default C ++ data types, such as: int, double, float, char, and so on.

Experience

  • Prefix and postfix difference is that, when used in conjunction with other operations when the prefix is ​​incremented to perform operations, the operations performed in conjunction; the suffix is ​​just reversed.
  • Formula prefix and postfix efficiency differences: 1) for built-in data types, no difference efficiency; 2) for self-defined data type, a higher efficiency of formula prefix.
  • Prefix and postfix efficiency distinguished essentially: returns a reference to type prefix, postfix return value is.
Published 271 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_17846375/article/details/104879088