0

For some reason when doing few calculations, I am getting the output that is not what was expected.

Here we calculate b from a=5, why are the outputs of b being different and why is it 28 when it should be 26 (12+14) but is it being 26 when done separately. Even after removing the brackets when calculating in one line, it gives the same output (28)

The code for the calculations that I did-


int main()
{
    int a, b;
    a = 5;
    b = 2 * ++a;   //first part of the calculation
    std::cout << a << std::endl;
    std::cout << b<<std::endl;  
    b =b+2 * ++a;  //second part of the calculation
    std::cout << a << std::endl;
    std::cout<<b<<std::endl; //It is coming as 26 when done separately

    //RESTARTING THE OPERATION FROM SAME VALUES TO FIND B IN ONE LINE

    a = 5;
    std::cout << 2 * ++a << std::endl;
    std::cout << 2 * ++a << std::endl;
    a = 5;
    b = (2 * ++a) + (2 * ++a); //b being calculated in one line
    std::cout << a << std::endl;//But 28 when done in one line
    std::cout << b;
    return 0;
}
  • 2
    `(2 * ++a) + (2 * ++a);` is undefined behaviour. – Quimby Sep 03 '22 at 18:04
  • *it should be 26*. This is incorrect, your code has undefined behaviour. – john Sep 03 '22 at 18:07
  • `a + ++a` is [undefined behavior](https://en.cppreference.com/w/cpp/language/operator_incdec), let alone `(2 * ++a) + (2 * ++a)`. – Matt Sep 03 '22 at 18:13
  • Why bother? Just do `b = 4 * a + 6;` if that is the result you want. – BoP Sep 03 '22 at 18:19
  • @BoP My roommates are learning C++, they asked me why it was happening, and I wasn't able to understand which is why I posted it here, otherwise I would have also used a general way to calculate it too – Arjun Agnihotri Sep 03 '22 at 18:59

0 Answers0