1

I would like to find an efficient way to limit the values of the members in a struct. So far I am checking all the members one by one with "if-esle if" for min max values

if(months.January>31)
{
January=31
}
else if(months.January<1)
{
January=1;
}
if(months.February>28)
{
February=28
}
else if(months.February<1)
{
February=1;
}
Spitfire1.2
  • 107
  • 5
  • 3
    If you have named the month members explicitly, then no. You could use one array for the values per month, and another array giving the max day for each indexed month, and use a loop to check the ranges. With a special case for February. Such as `int maxday[12] = { 31, 28, 31, 30 ... };` etc. – Weather Vane Jun 23 '21 at 08:48

3 Answers3

4

If you're repeating code that does the same thing, put it in a function:

int clamp(int val, int min, int max)
{
  if (val < min) return min;
  if (val > max) return max;
  return val;
}

and just write

months.January = clamp(months.January, 1, 31);
months.February = clamp(months.February, 1, 28);

or, as this is still pretty repetitive, move those hardcoded values in to arrays and write a loop:

for (int i = 0; i < NumMonths; ++i)
{
    month[i] = clamp(month[i], month_min[i], month_max[i]);
}

(I guess min will always be 1, so using an array for that is probably unnecessary. Still, you get the idea).

Useless
  • 64,155
  • 6
  • 88
  • 132
2

These are some macros that I been using since forever, for min, max and clamp.

#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#define CLAMP(x, lower, upper) (MIN((upper), MAX((x), (lower))))

So, for your january example:

months.January = CLAMP(months.January, 1, 31);
Tinchetsu
  • 116
  • 1
  • 3
1

The only more efficient way I could think of than the way you followed, is using ternary operators instead of if-else if statements. Like this:

January = (months.January > 31) ? 31 : months.January;
January = (months.January < 1) ? 1 : months.January;
February = (months.February > 28) ? 28 : months.February;
February = (months.February < 1) ? 1 : months.February;

Here is an article on Wikipedia if you don't already know what ternary operators are.

  • nitpicking: `more **efficient** way` It's not more efficient, may be less efficient, cause there are more assignments, but it could be more like "concise". Anyway, you could chain it `x = x > 31 ? 31 : x < 1 ? 1 : x;` – KamilCuk Jun 23 '21 at 08:57