有关C运算符的疑问

有关C运算符的疑问

问题描述:

int _tmain(int argc, _TCHAR* argv[])
{
	int a=5;
	printf("%d,%d,%d,%d",a++,++a,a--,--a);//4,5,4,5
	printf("\na++-%d",a++);//5
	printf("++a-%d",++a);//7
	printf("a---%d",a--);//7
	printf("--a-%d",--a);//5
return 0;
}



在同一行中单独打印时输出如何变化?输出在注释部分给出




How the output varies when in same line and printed seperately?? Output is given in commented part


Guidance will be helpful

"x ++"和"++ x"是postfixprefix增量运算符.
"x ++"采用值"x",然后将"x"加1,但返回原始值.
所以
"x++" and "++x" are postfix and prefix increment operators.
"x++" takes the value of "x", then increments "x" by one, but returns the original value.
So
x = 6;
a = x++;

最终以包含6的"a"和包含7的"x"结尾.
"++ x"递增"x"的值,然后返回新值.
所以

ends up with "a" containing 6, and "x" containing 7.
"++x" increments the value of "x" and then returns the new value.
So

x = 6;
a = ++x;

以包含7的"a"和包含7的"x"结尾.
尽管printf的每个参数都是单独评估的,但不必按照您编写它们的顺序从左到右进行评估,因此,第一行中的奇数值.
其他很明显:a输入为5,在使用该值后将第一个添加为1,将第二输入为6,并在使用该值并添加"7"之前将其添加.然后,它以7的形式输入第三位,并在使用该值后递减,因此以6的形式输入最后的1,在使用该值之前将其递减,以便将其打印为"5".

ends up with "a" containing 7, and "x" containing 7.
Although each parameter for printf is evaluated separately, they do not have to be evaluated in the left-to-right order you wrote them, hence the odd looking values in your first line.
The others are obvious: a enters as 5, is incremented the the first one after the value is used, enters the second as 6 and is incremented before the value is used and "7" printed. It then enters the third as 7 and is decremented after the value is used, so enters the final one as 6, which is decremented before it is used so it is printed as "5".


冒着做我也是"的风险,在本次讨论中没有人提到(再次!)提到的顺序点. 分配操作员的异常行为 [
At the risk of doing a "me too" no one''s mentioned sequence points (again!) in this discussion. Assignment operator unusual behaviour[^] has a previous answer for the last poor mug to get asked this with a reference about them.

Cheers,

Ash



i ++可能比++ i慢,因为可能需要保存i的旧值以供以后使用,但实际上所有现代编译器都会对此进行优化.

也许会对您有帮助:

http://*.com/questions/24853/what-is- the-difference-between-i-and-i [ ^ ]

http://www.eskimo.com/~scs/cclass/notes/sx7b.html [^ ]

问候,
亚历克斯
Hi,
i++ could potentially be slower than ++i, since the old value of i might need to be saved for later use, but in practice all modern compilers will optimize this away.

Maybe it will help you:

http://*.com/questions/24853/what-is-the-difference-between-i-and-i[^]

http://www.eskimo.com/~scs/cclass/notes/sx7b.html[^]

Regards,
Alex