一元运算符的区别(+ =,= +,++ x,x ++) [英] Difference of Unary operators ( += , =+ , ++x , x++ )

查看:56
本文介绍了一元运算符的区别(+ =,= +,++ x,x ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中这些一元运算符有什么区别?.你能给我提供例子吗?

What is the difference between these unary operators in C# ? . Can you provide me with example?

请提供每个的名称.:)

Please provide the name of each. :)

+ = vs = +

+= vs =+

++ x与x ++

++x vs x++

推荐答案

这无疑已经得到了回答,但是无论如何...

This has no doubt been answered before, but anyway...

它们在更改值和返回结果的方式上有所不同.

They differ in how they change the value and how they return the result.

前两个 + = = + 的行为方式是第一个增加变量,另一个设置变量.它们没有关系.观察以下代码:

The first two += and =+ behave in the way that the first increments a variable, the other sets a variable. They are not related. Observe the following code:

// +=
x = 1;
printf( x += 1 ); // outputs 2, the same as x = x+1
printf( x );      // outputs 2

// =+
x = 1;
printf( x =+ 1 ); // outputs 1, the same as x = 1;
printf( x );      // outputs 1

接下来的两个 ++ x x ++ 的功能顺序不同. ++ x 将变量加1并返回结果. x ++ 将返回结果并加1.

The next two, ++x and x++, differ in the order their function. ++x will increment your variable by 1 and return the result. x++ will return the result and increment by 1.

// ++x
x = 1;
printf( ++x ); // outputs 2, the same as x = x+1
printf( x );   // outputs 2

// x++
x = 1;
printf( x++ ); // outputs 1
printf( x );   // outputs 2

它们对于 for 循环和 while 循环最有用.

They are mostly useful for for loops and while loops.

在速度方面,认为 ++ x x ++ 快很多,因为 x ++ 需要创建一个内部临时变量来存储值,增加主变量,但返回临时变量,基本上使用更多的操作.我很久以前才了解到这一点,我不知道它是否仍然适用

In terms of speed, ++x is considered a lot faster than x++ since x++ needs to create an internal temporary variable to store the value, increment the main variable, but return the temporary variable, basically more operations are used. I learned this a looong time ago, I don't know if it still applies

这篇关于一元运算符的区别(+ =,= +,++ x,x ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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