1

The output is 34, but how is this expression evaluated?

How would it be with parentheses?

The correct operator precedence is:

a += ((((((2 * i++) % 5) * 4) + (--j)) - (3 / k)) + 2);

But I think correct should be:

a += (((((2 * i++) % (5 * 4)) + (--j)) - (3 / k)) + 2);

#include <iostream>
using namespace std;

int main()
{
    int a = 3, i = 12, j = 14, k = 16;
    a += 2 * i++ % 5 * 4 + --j - 3 / k + 2;
    cout << a;
}
5
  • 3
    You may check docs if you have any doubts. It describes both precedence and associativity.
    – user2956272
    Commented Nov 9, 2019 at 23:22
  • What do you think it should be and how do you come to that conclusion? Commented Nov 9, 2019 at 23:35
  • I edited my post.
    – Hadi
    Commented Nov 9, 2019 at 23:36
  • Usually I'm one of the first downvoters but in this question I don't understand the downvotes. Could someone explain it to me? Commented Nov 9, 2019 at 23:52
  • The title ought to be more specific. Commented Jun 6, 2024 at 14:23

1 Answer 1

3

The operators *, / and % have same precedence and are grouped left to right. Therefore it is ((2 * i++) % 5) * 4 and not (2 * i++) % (5 * 4)

2
  • 1
    in the language of the standard, those operators are grouped left to right. “Evaluated” is easily misread here to suggest order of evaluation of their arguments, which is an entirely different matter. +1. Commented Nov 9, 2019 at 23:47
  • 1
    @PeteBecker Changed it. Commented Nov 9, 2019 at 23:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.