How to limit a data type to a particular range?

Hello, for example I have a data type int x.
I would like to increment x or decrement x based on other comparison.
However I only want the range of x to only be from 0 - 255.

I've check out some solutions like,

constrain(x, a, b), so it'll be like

int x = constrain(x, 0, 255);

If that works, where should i write this line at? Does declaring it as a global variable work fine?
If not, is there another better/simpler method?

Why not just use a byte?

saximus:
Why not just use a byte?

Hmm.. what happens when a byte is at 255 and you increment it? Does it stay 255 or will it be 256?

Why not not increment the variable if it's value is already 255?

PaulMurrayCbr:
Why not not increment the variable if it's value is already 255?

Alright so I'll output a pwm value which is 0 - 255.
This is a part of my code.

void compareNOVno(void)
{
  if(pv_Vnew > pv_Vold)
  {
    --pwm;
  }
  else
  {
    ++pwm;
  }
}

void loop() 
{
   reading();
   PowerCalculation();

   if(pv_NewP > pv_OldP)
   {
      compareNOVyes();
   }
   else
   {
      compareNOVno();
   }

   pv_OldP = pv_NewP;
      
}

I get that using byte might work,
if I were to not not increment the value where should I check the value to not allow the value to increase again?

where should I check the value to not allow the value to increase again?

Either just before you increment it, and then don't do the increment, or after the increment and reset its value to the maximum if it has gone out of range.

Note that if you increment a byte variable with a value of 255 it will roll over to zero.

bryanyon:
Does declaring it as a global variable work fine?

Depends on what you want. Only use a global if you need it global. If you only use it in one function, don't make it global :wink:

byte addTest = 255 + 1; //==> gives 0
byte subTest = 0    - 1; //==> gives 255

But I would say a byte is best if you just add or subtract 1 as you do. Simply only add when it's not 255 and subtract when it's not 0.

void compareNOVno()
{
  if(pv_Vnew > pv_Vold && pwm != 0)
  {
    --pwm;
  }
  else if(pwm != 255)
  {
    ++pwm;
  }
}

Btw, terrible variable and function names. They should exactly tell wat they do or what they hold. "compare" is fine but what is "NOVno"????

Hmm.. what happens when a byte is at 255 and you increment it? Does it stay 255 or will it be 256?

You could have written a sketch to test that in not much more time than it took to ask the question.