How to Properly Use OR Operators in C++?

0
8
Asked By CodingNinja92 On

I'm having trouble with my C++ program that's supposed to check if a month is between March and June, and I want to determine if a day is valid. I'm getting an error about no match for operator, and I think the issue is in my if statements. Here's the part of the code that I'm unsure about:

```cpp
if ( (inputMonth = "March") || (inputMonth = "April") || (inputMonth = "May") || (inputMonth = "June") ) {
springMonth = true;
}

if ( (inputDay >= 1) || (inputDay <= 30) ) {
validDay = true;
}
```

I feel there's something wrong with the way I'm checking the strings and the conditions. Can anyone help me understand what's going wrong?

2 Answers

Answered By CodeWizard123 On

Your code won't compile because you're doing assignments in your if statement instead of comparisons. Instead of using the assignment `=`, use `==` for comparisons. You can simplify your code to:

```cpp
const auto springMonth = (inputMonth == "March" || inputMonth == "April" || inputMonth == "May" || inputMonth == "June");
```

This way, `springMonth` is declared and initialized at once, and if the month is invalid, you don’t even need to check the day!

CuriousCoder -

Thanks for that explanation! But why go with `const auto` instead of just declaring it like I did?

Answered By TechieTommy On

You're actually using the assignment operator `=` instead of the equality operator `==`. In your if statement, you're assigning the value rather than checking if they're equal, which is why you're seeing that error. You should change it to `==` like this:

```cpp
if ( (inputMonth == "March") || (inputMonth == "April") || (inputMonth == "May") || (inputMonth == "June") ) {
springMonth = true;
}
```

LearningCurves -

Oh man, rookie mistake. Thanks for pointing that out!

AssertiveCoder -

Yes, that's the problem! The left side in your OR statement doesn't evaluate to a Boolean, so it leads to that error.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.