Addition assignment += behavior in expression

前端 未结 3 2080
你的背包
你的背包 2021-01-30 20:11

Recently I came across this question: Assignment operator chain understanding.

While answering this question I started doubting my own understanding of the behavior of t

3条回答
  •  猫巷女王i
    2021-01-30 20:46

    Following are the rules that need to be taken care of

    • Operator precedence
    • Variable assignment
    • expression evaluation

      Expression 1

      a = 1
      b = (a += (a += a))
      
      b = (1 += (a += a))  // a = 1
      b = (1 += (1 += a))  // a = 1
      b = (1 += (1 += 1))  // a = 1
      b = (1 += (2))  // a = 2 (here assignment is -> a = 1 + 1)
      b = (3)  // a = 3 (here assignment is -> a = 1 + 2)
      

      Expression 2

      a = 1
      b = (a += a) + (a += a)
      
      b = (1 += a) + (a += a) // a = 1
      b = (1 += 1) + (a += a) // a = 1
      b = (2) + (a += a) // a = 2 (here assignment is -> a = 1 + 1)
      b = (2) + (2 += a) // a = 2 (here here a = 2)
      b = (2) + (2 += 2) // a = 2
      b = (2) + (4) // a = 4 (here assignment is -> a = 2 + 2)
      b = 6 // a = 4
      

      Expression 3

      a = 1
      b = a += a += a += a += a
      
      b = 1 += 1 += 1 += 1 += 1 // a = 1
      b = 1 += 1 += 1 += 2 // a = 2 (here assignment is -> a = 1 + 1)
      b = 1 += 1 += 3 // a = 3 (here assignment is -> a = 1 + 2)
      b = 1 += 4 // a = 4 (here assignment is -> a = 1 + 3)
      b = 5 // a = 5 (here assignment is -> a = 1 + 4)
      

提交回复
热议问题