I would like to know the correct usage of conditionals such as if statements to avoid undefined behaviours. Let's start with an example:
uint8_t x = 0;
bool y = false;
bool z = false;
if ((x == 135) and !y and !z) {
//do something
}
else if ((x == 135) and y) {
x = 5;
z = true;
}
else if ((x == 5) and z) {
x = 135;
z = false;
}
else {
//do something
}
Now, will I get undefined behaviour by not including all 3 variables into every condition? Will every unaccounted for condition go into the else statement? If so, what happens if I get rid of the else statement? I have the exact same if statement (in a more complex scenario) and I seem not to be getting into the right statements every time.
Please enlighten me if there is a rule for this?
will I get undefined behaviour by not including all 3 variables into every condition?
The behaviour of not including all variables into every condition is not undefined by itself.
Will every unaccounted for condition go into the else statement?
Statement-false (i.e. the statement after the keyword else
) is executed if the condition is false.
what happens if I get rid of the else statement?
The execution continues from the statement after the if statement.