0

I am a newbie to C programming. Now, I am trying to understand the topic "C Operator Precedence and Associativity". Especially, I would like to pay attention to the order of evaluation with parenthesis, and why the didn't evaluate at first. I write the next example:

#include <stdio.h>

int main() {
  volatile int i = 10;
  i = i + i + i++ + (i *= 2);
  printf("%d\n", i); //52
  return 0;
}

As I understand from the book "The C Programming Language. 2nd Edition (THE ANSI C)", each operator has specific precedence and associativity. [C table](https://i.stack.imgur.com/LP8eY.jpg)By the rules, this expression must have the next evaluation order:
  1. First precedence has "i++", it must be evaluated at first;
  2. Second precedence has "(i *= 2)";
  3. And then the summation;

But why the compiler evaluates the expression in this order:
1(i) + 2(i) + 3(i++) + 4(i *= 2);

Explain me please.
Result is 52.
Expecting:

  1. (i *= 2), return 20 // i = 20
  2. i++, return 20 // i = 21
    21 + 21 + 20 + 20
Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
  • 5
    The behavior is undefined. Read about [sequence points](https://stackoverflow.com/a/3575375/1553090). – paddy Jul 17 '23 at 22:41
  • 2
    Using `-Wall -Wpedantic` will warn you when compiling this code: `warning: unsequenced modification and access to 'i' [-Wunsequenced]`. – Marco Jul 17 '23 at 22:42
  • 3
    My advice is to try to never write code like this for real world use even when it is valid code. Use parentheses, think twice about using i++ and ++i in expressions instead of on their own, etc., – Dave S Jul 17 '23 at 22:43
  • 3
    Fully agree with @DaveS. Smart code often is the worst kind of code. – Marco Jul 17 '23 at 22:43

0 Answers0