Sign in to follow this  

Checking for Negative Values ?

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

If the type of x is known at compile time, the compiler will usually adjust the comparison to avoid the implicit type conversion between float <-> int. So you could even do:

if (i < 0)
{
}


if i's type is known at compile time, 0 can be treated as a floating-point literal by the compiler.

Other than that, there's not really much more to say. That's how you compare negative values, as Fruny said. =)

Share this post


Link to post
Share on other sites
Do not optimize things like this when you do not know they are the source of the slowdown.

The compiler will almost *always* produce faster code when you are clear about what you're trying to do. Using something like the bitwise and operator is less clear to the compiler and will probably produce slower code.

Profile first, then optimize where you can see that there are actual slowdowns. Compiler writers know what they are doing; it's very rare that you'll need to write 'optimized' code until you've profiled and checked the compiler's (assembly) output.

Often slowdowns are due to inefficient algorithms. Rather than bithack to produce what you think is faster code, profile it to make sure there is a bottleneck there and choose a better algorithm if possible.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by Endemoniada
Hi,

I thought maybe you could check the signed bit and it would be faster.


You could certainly do that by use the & operator (x & 128 to check a bytes sign bit). I seriously doubt you'll gain any noticable increase in execution speed. Besides you'll end up user an if statement anyway so you may as well just cut out the extra step and go with if(x <

Share this post


Link to post
Share on other sites
Quote:
Original post by Anonymous Poster
You could certainly do that by use the & operator (x & 128 to check a bytes sign bit).

DANGER WILL ROBSIN: That's implementation specific. I can guarantee that won't work on all processors. Plus, it may even be slower (bitwise ops does not automatically imply fast). And you must adjust the number for anything larger than a byte.

Plus I wouldn't be suprised if you actually lost speed.

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this