• 13
• 15
• 19
• 27
• 9

# Getting rid of a minus sign

This topic is 3986 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I always thought unsigned int would get rid of the minus sign but it doesn't. e.g. unsigned int a = 12-13; cout << a; It outputs 42912121 or some weird value like that. So is there any other way to keep getting rid of the minus sign? The only thing I can think of is to square the negative value and then square root it. But that seems too inefficient. Brings me to another question... if you #include <cmath... we have sqrt(number) which gets the square root of something but how do you square a variable without doing expression*expression. Does it recalculate the value in each expression or does it do it just once?

##### Share on other sites
This is the kind of question that's going to get a billion responses: Let the race begin!

if(number < 0)
{
number = -number;
}
// Or
number = abs(number);
// Or
if(number < 0)
{
number *= -1;
}

##### Share on other sites
The difference between signed and unsigned is in how the first bit (most significant) of the number is interpreted. Negative numbers are stored in twos-complement form (http://en.wikipedia.org/wiki/Two's_complement).

Without going into detail, in two's complement form, -1 is stored as 0xFFFFFFFF. That is the value that will get stored into 'a'. When you then print 'a' out, it interprets it as an unsigned, which takes 0xFFFFFFFF => 2^32-1 = 4294967295.

To actually 'get rid of the minus sign' you are going to have to use the abs() function.

##### Share on other sites
For the reason you get that funky number, read up on Two's Complement.

To get the magnitude, or absolute, part of a number, you'll typically use a function called 'abs'; ie, abs(-39) will return 39.

##### Share on other sites
Quote:
 Original post by spaceJockey123Brings me to another question... if you #include

Yes, it does calculate the value of expression twice. Any decent optimizer should be able to recognize if the two expressions are the same, but any side effects will be evaluated twice. If I'm going to be squaring things a lot I find it useful to define:

template<class T> square(const T& a){  return a*a;}

Edit: although in fact to take advantage of NRVO it should be:

template<class T> square(const T& a){  T b(a);  b *= a;  return b;}