[英]Should I use x = -x, to convert a negative number to a positive number and vice versa (in C++)?
I was wondering if I should use this "x = -x" to convert a negative number to a positive number or a positive number to a negative number in C++.我想知道我是否应该使用这个“x = -x”在 C++ 中将负数转换为正数或将正数转换为负数。 I mean is working pretty well so far, but I'm not sure if is recommended or not.
我的意思是到目前为止工作得很好,但我不确定是否推荐。
I would appreciate some feedback about this thing.我会很感激一些关于这件事的反馈。 Thanks!!
谢谢!!
int x = 10;
if (x > 0) {
x = -x;
}
cout << x; // x = -10;
It is fine to do it that way.这样做很好。 You shouldn't have to worry about something like that.
你不应该担心这样的事情。 If you're worried about performance, you should either mesure performance or check what assembly it generates.
如果您担心性能,您应该测量性能或检查它生成的程序集。
I've created a compiler explorer example .我创建了一个编译器资源管理器示例。 It compares the assembly for both
x = - x;
它比较
x = - x;
的程序集x = - x;
and x *= -1;
并且
x *= -1;
. . You can clearly see, even if you don't know assembly, that it generates the same code.
即使您不了解汇编,您也可以清楚地看到它生成相同的代码。 And not very much of it anyway!
反正也不是很多! (And it goes away when optimiser flags are on.
(当优化器标志打开时它就会消失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.