Why this expression is processed from left to right?

Debojit Acharjee 455 Reputation points
2023-06-26T11:54:03.07+00:00

Any arithmetic operator in C has an associativity from right-to-left but why the expression in the following program is processed from left-to-right? The result of the math expression 6 - 2 + 4 is 0 according to BODMAS rule. Even if it's following the operator associativity and precedence rule the calculation should be done from right-to-left.

#include <stdio.h>

int main()
{
  int a;

  a = 6 - 2 + 4;

  printf("6 - 2 + 4 = %d", a);
  
  return 0;
}

Output:

6 - 2 + 4 = 8

Developer technologies | C++
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Olaf Helper 47,441 Reputation points
    2023-06-26T12:14:10.7833333+00:00

    6 - 2 + 4 is 0 according to BODMAS

    What are you talking? The calculation has only add/sub, no multiply, no division, no squard.

    Doesn't matter if evaluate it left-to-right or right-to-left, here comes the associative law in rule; the result is always 8.

    https://en.wikipedia.org/wiki/Operator_associativity


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.