0

In this program what I am adding a number to the z based on some criteria where if x == 10 add 20 else 30. I tried with ternary operator but the it is giving me wrong answer after removal of extra brackets

Code 1 - Using ternary operator with extra brackets ###

    int x=10;
    int z = 10 + ((x == 10)? 20: 30); // used brackets here
    std::cout << z << std::endl; // output = 30, it is correct

Code 2 - Using ternary operator without extra brackets (Wrong result) ###

    int x=10;
    int z = 10 + (x == 10)? 20: 30; // not used brackets here 
    std::cout << z << std::endl; //output = 20; expected is 30
user438383
  • 5,716
  • 8
  • 28
  • 43
Gopi Sai
  • 75
  • 1
  • 7
  • 7
    Have a look at operator preceedence please. – πάντα ῥεῖ Oct 16 '22 at 06:28
  • 2
    https://en.cppreference.com/w/c/language/operator_precedence – Retired Ninja Oct 16 '22 at 06:30
  • 1
    [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) - *Never*, ever include that header! – Jesper Juhl Oct 16 '22 at 06:33
  • 1
    [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Jesper Juhl Oct 16 '22 at 06:34
  • the answer for this question is ternary operator precedence from right to left, addition or substraction precedence from left to right, without brackets the ternary operator treated from right to left so we got 20 as output in program 3 – Gopi Sai Oct 16 '22 at 06:40
  • 2
    I am not sure why this question was closed. It is reproducible and the answer is simple, precedence of trinary operator is higher so the expression actually interpreted as this: `int z = (10 + (x == 10)) ? 20 : 30;` which means it will always be true because any bool + 10 will always result in `true`. – Ashutosh Raghuwanshi Oct 16 '22 at 06:56

0 Answers0