如何preFIX(++ x)和后缀(X ++),操作的工作? [英] How do Prefix (++x) and Postfix (x++) operations work?

查看:165
本文介绍了如何preFIX(++ x)和后缀(X ++),操作的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我如何preFIX /后缀运营商真的管用吗?我一直在寻找网上很多,但没有发现任何东西。

Can someone tell me how prefix / postfix operators really work? I've been looking online a lot but haven't found anything.

这是我可以告诉prefex先递增,然后进行操作,然后分配。结果
后缀会做第一次操作,然后分配,然后递增。

From what I can tell prefex first increments, then does the operation and then assigns.
Postfix would do the operation first, then assign and then increment.

但我有一点麻烦与我的code:

But I'm having a bit of trouble with my code:

int x, y;
x = 1;
y = x + x++; // (After operation y = 2)(x=2)

然而,当我做的:

However when I do:

y = x++ + x; // (After operation y = 3)(x=2)

我不知道为什么这些操作会有什么不同。我有两个问题:

I'm not sure why these operations would be any different. I have two questions:


  • 您能解释的区别?

  • Could you explain the difference?

这怎么也适用于其他运营商preFIX?

How does this apply to the other operator Prefix?

推荐答案


  • 在C# + 的操作数左到右的顺序evaulated。

  • 在C和C ++评价为 + 的操作数的顺序是unspecifed。

  • In C# the operands of + are evaulated in left-to-right order.
  • In C and C++ the order of evaluation for the operands of + is unspecifed.
  • 对于C#你的例子的工作方式如下:

    For C# your examples work as follows:

     y = x + x++;
         ^ x is 1
             ^ x is increased to 2, but the postfix increment returns the old value (1)
     y = 2
    
     y = x++ + x;
         ^ x becomes 2, but postfix increment returns the old value (1)
               ^ x is now 2 here
     y = 3
    

    这篇关于如何preFIX(++ x)和后缀(X ++),操作的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆