Is there a way to make the operator in a if statement variable?
Lets say i want to easily change multiple operators from < to >.
Depending on a variable, you can used a switch/case to select code needing to execute.
.
Is there a way to make the operator in a if statement variable?
Lets say i want to easily change multiple operators from < to >.
#define OPToday <
if(thisValue OPToday thatValue)
{
}
Next day, all you need to change is the value associated with the name OPToday.
Though the whole idea of changing operators does not make sense.
I would do something like this:
#define MAKE_EQUALS 0
#define MAKE_GREATER 1
#define MAKE_LESS 2
int doCondition(int val1, int val2, int condition)
{
if (condition == MAKE_EQUALS) return (val1 == val2);
if (condition == MAKE_GREATER return (val1 > val2);
if (condition == MAKE_LESS return (val< val2);
return 0;
}
No.
But, we have the ternary operator which will allow you do construct an expression to do what you want
if(using_gt ? (a>b) : (a<b)) {
}
That is clever!
Hi,
Pauls idea is cool.
Also, inequalities have a kind of logic to them just like equalities.
If we have:
a=b
then when we operate on both sides at the same time as long as we do the same operation on both sides the equality remains valid, and this includes swapping a and b.
Inequalities are different though. They stay the same when we do certain operations and actually change when we do other operations.
For example if we have:
a>b
and we swap a and b, we then see that the following is true:
b>a
If we find that a>b is not true and after the swap a<b is not true, then that means that a=b is true.
So there are different ways of looking at this.
There is also "greater than or equals to" and "less than or equals to" to deal with.
Another idea would be to use subtraction instead of inequalities:
c=a-b
possible results:
sign of c=-1, then a was less than b
sign of c=+1, then a was greater than b
sign of c=0, then a was equal to b
anda702:
Is there a way to make the operator in a if statement variable?
Lets say i want to easily change multiple operators from < to >.
An important consideration is when you are going to be changing them. Are you changing them at compile time for development purposes? Will you be changing back and forth frequently, or do you just need to change them once because you goofed and need to fix a mistake? Or are you trying to reconfigure your logic dynamically at run time?
The best method will depend on exactly what you are trying to do.