Associativity math: (a + b) + c != a + (b + c)

前端 未结 6 1076
北荒
北荒 2020-12-15 02:40

Recently I was going through an old blog post by Eric Lippert in which, while writing about associativity he mentions that in C#, (a + b) + c is not equivalent

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 03:24

    A couple of similar examples:

    static void A(string s, int i, int j)
    {
      var test1 = (s + i) + j;
      var test2 = s + (i + j);
      var testX = s + i + j;
    }
    

    Here A("Hello", 3, 5) leads to test1 and testX being equal to "Hello35", while test2 will be "Hello8".

    And:

    static void B(int i, int j, long k)
    {
      var test1 = (i + j) + k;
      var test2 = i + (j + k);
      var testX = i + j + k;
    }
    

    Here B(2000000000, 2000000000, 42L) leads to test1 and testX being equal to -294967254L in usual unchecked mode, while test2 becomes 4000000042L.

提交回复
热议问题