Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check multiple OR operators in IF statement

I have the following C++ code:

if(x==y||m==n){
cout<<"Your message"<<endl;
}

If x is equal to y or m is equal to n, the program prints "Your message". But if both conditions are true,the program tests only one of them and eventually prints one "Your Message".

Is there a way to print each "Your message" independently based on each condition using a single if statement?

The output would be identical to the below using multiple if statements.

if(x==y){
cout<<"Your message"<<endl;
}

if (m==n){
cout<<"Your message"<<endl;
}

1 Answers

Not that I'd ever do it this way, but ...

for(int i = 0; i < (x==y)+(m==n); ++i) {
  std::cout << "Your message\n";
}


Let me expand on this. I'd never do it this way because it violates two principles:

1) Code for maintainability. This loop is going to cause the maintainer to stop, think, and try to recover your original intent. A pair of if statements won't.

2) Distinct input should produce distinct output. This principle benefits the user and the programmer. Few things are more frustrating than running a test, getting valid output, and still not knowing which path the program took.

Given these two principles, here is how I would actually code it:

if(x==y) {
  std::cout << "Your x-y message\n";
}
if(m==n) {
  std::cout << "Your m-n message\n";
}

Aside: Never use endl when you mean \n. They produce semantically identical code, but endl can accidentally make your program go slower.

like image 91
Robᵩ Avatar answered Apr 23 '26 02:04

Robᵩ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!