Mathematical operation to save a number not less than zero

In programming, the module is useful for storing numbers in a range not exceeding the upper limit of the boundary.

For instance:

int value = 0;
for (int x=0; x<100; x++)
    cout << value++%8 << " "; //Keeps number in range 0-7

Output: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7...


Now consider this situation:

int value = 5;
for (int x=0; x<100; x++)
    cout << value-- << " ";

Output: 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7...

My question is: how to set the lower limit to 0 WITHOUT using any conditional statement like if or switch case?

The output I want: 5 4 3 2 1 0 0 0 0 0 0 0 ...

+4
source share
5 answers

How about std::max?

int value = 5;
for (int x=0; x<100; x++) {
    cout << value << " ";
    value = std::max(0, --value);
}
+4
source

Use std::max(value,0)or ternary operator. Both will compile code without conditional branching.

+1
source

,

typedef unsigned u32b;

u32b sat_subu32b(u32b x, u32b y)
{
    u32b res = x - y;
    res &= -(res <= x); 
    return res;
}

. , , -, ;

u32b sat_dec(u32bx)
{
    u32b res = x-1;
    res &= -(res <= x); 
    return res;
}

, , .

+1

. , % 0 7, , , max.

, , :

int value = 5;
for (int x=0; x<100; x++)
    cout << value > 0 ? value-- : 0 << " ";

, value 0.

std::max:

int value = 5;
for (int x=0; x<100; x++)
    cout << std::max(0, value--) << " ";
0

max std.
max :

template <class T> const T& max (const T& a, const T& b) {
  return (a<b)?b:a;     
}
0

Source: https://habr.com/ru/post/1534853/


All Articles