Question

I am trying to write a C function which checks if a int is positive or not. This is what i have:

int isPositive(int x){
    return ~(x >> 31) & 0x1;
}

Depending on the number, this should return 1 is positive and 0 is not. It works for all the numbers but not for -2147483648.

That number should fit in a 32bit vector with 2's complement. So why isn't it working?

To be precise, im in Visual Studio and it gives me a compile error of C4146: unary minus operator applied to unsigned type, result still unsigned however -2147483647 seems to work.

Was it helpful?

Solution

How did you enter the -2147483648? If you just typed it directly into your program, that would be the unary - applied to the literal, not a literal including the -. Since 2147483648 doesn't fit in an int, your literal gets the unsigned type.

Either use INT_MIN, or use the trick most libraries use to define it:

 isPositive(-2147483647 - 1);

OTHER TIPS

Since C makes absolutely no guarantees about either the size of int or the numerical system used to store numbers (sign bit or otherwise), if you are trying to do this for any practical purpose, you probably shouldn't, use direct comparison with 0 for maximum portability. Even extending your type to a larger one to "protect" against overflowing is not going to help as C has very few guarantees about sign bit propagation and such.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top