简体   繁体   中英

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++. 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; and 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM