Reputation: 109
For example I want to check the following:
if((sample.x == 260 || sample.x == 261) && (sample.y==178 ||sample.y==179 ||) )
{ ...
}
How can I put it in a simpler way?(It's a lot of OR that I have to put in the if condintion, should I make a function? or how can I say something like :
if(sample.x == 10 between 20)//Thats my objective here
Thanks!
I am programming in C
Upvotes: 1
Views: 754
Reputation: 6776
This is a common problem when trying to write readable code. If the values naturally fall into ranges, you can do something like this
if ((x >= 10 && x < 20) && (y >= 30 && y < 40))
{
...
}
Sometimes the logic is more complicated. In this case, you can have a long expression inside your if statement, but this can be hard for other programmers (or you) to read. A technique I like is to break up the condition into a series of predicates and compute each on a separate line:
/* get the bool type for readability */
#include <stdbool.h>
bool x_in_range = (x >= 10 && x < 20) || (x >= 100 && x < 110);
bool y_in_range = (y >= 30 && y < 40) || (y >= 200 && y < 210);
if (x_in_range && y_in_range)
{
....
}
This can make complex logic easier to follow. Simple memoized expressions like this should be easy for the compiler to optimize and generate comparable code to putting everything inside the if statement.
Lastly, if the set of conditions that trigger your if statement are really complex, you might want to encode them into a table and then write a small engine to evaluate the variables in question against the data in the table. This is a data-driven approach. In your case, the table might include a set of acceptable ranges for the x and y variables. This table and its evaluation engine might best be factored out into a separate function.
Upvotes: 0
Reputation: 1211
You could make a macro for that.
// define macro between, you get X<=V && V<=Y
// X, Y are the limits, V is the variable you are evaluating
#define between(V, X, Y) ((X)<=(V) && (V)<=(Y))
this returns true if variable V is between X and Y, false otherwise.
Then you can use this as a normal function
if(between(sample.x, 10, 20) || between(sample.y, 30, 40)) {...}
More info about macros here
Upvotes: 3
Reputation: 2377
You could just check a range instead of each individual value, for example:
if ((sample.x >= 10 && sample.x <= 20) && (sample.y >= 178 && sample.y <= 200))
{
// ...
}
Upvotes: 0