``````if (x <= 22.5f)
{

}
if (x >= 22.5f && x <= 67.5f)
{

}
if (x >= 67.5f && x <= 112.5f)
{

}
if (x >= 112.5f && x <= 157.5f)
{

}
if (x >= 157.5f && x <= 180.0f)
{

}``````

My code seems too complex in its current form. I reckon there must be a more efficient way of doing the above. Can someone lend me their ideas?

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by DaveTran

Two things

``````if (x <= 22.5f)
{
}
if (x >= 22.5f && x <= 67.5f)
{
}``````

In statements like these, if the value is exactly 22.5f, then you're allowing control to enter each of these if statement. One way of stating intent is if one statement is <=, then the next one should simply be >. We could fix that up and call it a day. But we won't.

The second thing is that you are using seperate if statements for each check. Even if the value fits the first if statement, the way your program is constructed means that every following statement is still going to be evaluated. Rewrite the remaining statements as "else if". That way, when control finds a valid condition, none of the others are checked. Also, doing so means you can drop the first part of the conditional. if x <= 22.5f, you know control will enter the first block. So the second check does not need to worry about x being > 22.5, only if it is less than 67.5f.

``````if (x <= 22.5f)
{
}
else if (x <= 67.5f)
{
}
else if (x <= 112.5f)
{
}
else if (x <= 157.5f)
{
}
else if (x <= 180.0f)
{
}``````

Edited by apegram: n/a