Problems with "or" in C++

Asked

Viewed 1,348 times

9

I need to make an algorithm that gets 3 different numbers, and if it gets repeated numbers, it gives an error message.

My program is all working properly, but when I put such a line to warn of the error I try to use Or and it doesn’t work. Here’s what I’m typing

if (z==x) or (y==z) or (x==y);
    cout << "\nErro. Os valores devem ser diferentes. Tente novamente: \n" << endl;

Even if there’s an easier way than or, you could kindly tell me how the insertion of the or in C++ ?

According to Code::Blocks, the program expects a primary expression before the or.

  • You don’t need to do this now or if you don’t think you should but if the answer has served you well you can accept it as correct. And you can vote for all the posts on the site that helped in any way. Check out the [tour].

  • 1

    in fact, your problem is not exactly with the OR operator; it is, as you wrote if. If you did if (z==x or y == z or x == y) Cout.... would have no problem.

3 answers

16


The preferred syntax of or in C++ is || although they are synonymous.

In addition there was a ; that was closing the if and not performing as it seems to be your wish. The message was not being part of the conditional block.

There is also a problem with parentheses. A single pair must contain the whole condition. You could even put extra parentheses in the sub-expressions but they’re totally unnecessary.

Then your line would be:

if (z==x || y==z || x==y)
    cout << "\nErro. Os valores devem ser diferentes. Tente novamente: \n" << endl;

I put in the Github for future reference.

Keys could be recommended to encapsulate the block even having only one line. This avoids some errors by carelessness. Even if you choose not to use keys it would be interesting to place the block that should be executed conditionally on a new indented line as shown above.

4

The logical operator OR in C++ is ||.

if(z == x || y == z || x == y) {
  cout << "\nErro. Os valores devem ser diferentes. Tente novamente: \n" << endl;
}

You are also adding one ; after the if. This will cause this line to close there and Cout will always print the message, regardless of the outcome of the if.

0

If using C++ 11/14, you can use or( || ) and and and( && ) normally if you want.

  • Take a look at the other answers that are already here. If you think it’s worth submitting one more answer, please explain better. See you later. (ah, and coming!)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.