Search code examples
cstructlimitminmaxclamp

how to limit(clamp) struct values in C


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;
}

Solution

  • 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);