I have two cases in a program I am writing where i am using compound logical operators to compare a variable against multiple values efficiently. One of the is working just fine. I have an array of characters, and I want to check if one of the elements is equal to one of two values without having to restate the variable. I also have an integer called hourInt, but this is not important. The code I used for the conditional is as follows:
if (charArray[8] == 'P' || 'p' && hourInt != 12){
hourInt += 12;
}
if (charArray[8] == 'A' || 'a' && hourInt == 12){
hourInt -= 12;
}
And both of these conditionals perform their job correctly - they check whether charArray[8] is equal to one of the two values. But then, later on in the program, I tried using compound logical operators again. I have a two-character string called meridies, and I want to see whether it is not equal to one of four values. I set up a conditional with compound logical operators as follows:
if (meridies != "AM" || "am" || "PM" || "pm"){
cout << "Error: Unknown value for the meridies." << endl;
return inputTime();
}
Unlike the first conditional, which correctly compared the values, this second one always returns true, even if meridies is indeed equal to one of the four cases. I know I could just set this up as four different comparisons each with their own logical operator, but I am just wondering why this second conditional doesn't work whereas the first one does.
Yeah, you might need to read up on how operators work (and operator precedence).
Firstly, this is a nonsense:
charArray[8] == 'P' || 'p'
You are saying, if (charArray[8] == 'P') is true, or 'p' is true. 'p' will always be true, because it is not zero. It's not entirely clear what you are trying to do with that code, but I assume something along these lines?
if ( (charArray[8] == 'P' || charArray[8] == 'p') && hourInt != 12)
As for this:
if (meridies != "AM" || "am" || "PM" || "pm")
IF meridas is a std::string, then it should be:
if (meridies != "AM" && meridies != "am" && meridies != "PM" && meridies != "pm")
If however meridies is a char array, then you should be doing:
if (strcmp(meridies, "AM") != 0 &&
strcmp(meridies, "am") != 0 &&
strcmp(meridies, "PM") != 0 &&
strcmp(meridies, "pm") != 0)