Validating Variable Data Type and Content

Hi Particle Community,

Hope you are well,

I am trying to improve the robustness of a conditional statement:

if (reservation[day-1][period] == 0) {
  if (pirState == HIGH) {
    //Notification Module not implemented, therefore tested using Serial output.
    Serial.println("Vacant. No movement detected.");
  } else {
    //Notification Module not implemented, therefore tested using Serial output.
    Serial.println("Vacant. Movement detected.");
  }
} else if (reservation[day-1][period] == 1) {
  //Notification Module not implemented, therefore tested using Serial output.
  Serial.println("Reserved.");
}

The two values that are considered are day and period. Both of these variables should be integers where day is between 1-7 and period is between 0-5. I am looking for a method to check whether these variables fit between these values and that they are integers?

Any ideas would be appreciated,

Thank you,

Sam

If these variables are declared int there is no need to check whether they are intergers - they can’t be anything else but.

What do you want to do when your values don’t fit your pattern?
If you just want to constrain the values to the allowed ranges you can use the constrain() function.
If you want to check for disallowed values to refuse the entry and demand a correct value, I personally use this syntax

  // is value BETWEEN lowBound and hiBound (inclusive)
  if (lowBound <= value && value <= hiBound) {
    // value fits
  }
  else {
    // disallowed
  }
1 Like

Hi Sam,
reservation appears to be a multi dimensional array. Since C/C++ is static type casting it would not be required to check the type of the variables defined in that multi dimensional array. Where is this multi dimensional array defined in your application and how is it defined?

As for checking if the int is within a range I would probably just do a simple if check like this:
if((day-1) > 0 && (day-1) < 8 && period >= 0 && period < 6)
Bit long winded but it works.

Hope this helps.

1 Like

Hi @ScruffR,

Thank you for your tip,

It has worked really well.

Sam

Hi @IOTrav

Thank you, I have taken what you have both said and it is working without error now. :slight_smile:

Sam