Problems with "or" in C ++

9

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

My program is all working properly, but when I put the line to warn of the error I try to use Or and it does not 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 though I have an easier way than or , could you kindly tell me how to or insert in C ++?

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

    
asked by anonymous 06.03.2015 / 01:12

3 answers

15

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

Furthermore, it had a ; that was closing if and not running as it seems to be. The message was not part of the conditional block.

There is also a problem with the parentheses. A single pair should contain the entire condition. You could even put extra parentheses in the subexpressions but they are totally unnecessary.

Then your line would look like:

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

Keys could be recommended to encapsulate the block even though it has only one row. This avoids some mistakes 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 line with indentation as demonstrated above.

    
06.03.2015 / 01:20
4

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

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

You're also adding ; after if . This will cause this line to be closed there and cout will always print the message, regardless of the result of the evaluation of if .

    
06.03.2015 / 01:20
0

If you are using C ++ 11/14, you can use or (||) and and (& &) as usual.

    
21.06.2016 / 13:32