Home > Software design >  basic mathematics c code for moving left or moving right for same if condition (k*x<b*k); k =1
basic mathematics c code for moving left or moving right for same if condition (k*x<b*k); k =1

Time:09-22

Below is a simple program.

int main()
{
    int x, b = 3; //size_t x; size_t b = 3;
    
    char const *c = "moving_left"; // "moving_right"
    int k, border;
    
    if (!strcmp(c,"moving_left"))
    {
        k = 1;     // moving left
        border = 0;
        x = 5;
        
    }
    else
    {
        k=-1;     // moving right
        border = 7;
        x = 1;
    }
    

    while(true)
    {
        if (k*x<b*k)
        {
            cerr<<c<<x<<'\n';
            if (x==border){break;}
        }
        x-=k;
    }
    return 0;
}

When I'm moving left, i.e., x is decreasing, I want to print "moving_left" after x falls behind b (x<b).

And when moving right, i.e., x is increasing, I want to print "moving_right" after x crosses b (x>b).

The above program works fine when x & b are signed integers, but might fail when I declared them as unsigned integers (size_t) because of int promotion (when k = -1).

I want to run the above code in a single while loop for unsigned x & b (I like to declared them as unsigned because they are indices of unmentioned arrays). Also, in the if condition (kx<bk), I want left than sign (<).

Multiplying by negative one works only for signed integers. Is there any math trick to make the above code work for unsigned integers with said conditions?

CodePudding user response:

It is not completely clear why you want to use unsigneds and why you want so much to keep the condition (k*x<b*k) rather than something along the line of if ( (moving_left && x<b) || (!moving_left && b<x).

Anyhow if you want to use unsignds and you want to use a single condition for both cases, then you can add a level of indirection:

size_t x;
size_t b = 3;

bool move_left = true;
int border;

if (move_left) {
    x = 5;
    border = 0;
    upper = b;
    lower = x;        
} else {
    x = 1;
    border = 0;
    upper = x;
    lower = b;
}
    
while(true) {
    if (lower < upper) {
        std::cerr<<x<<'\n';
        if (x==border){break;}
    }
    x-=k;
}
  • Related