When (a+b)+c != a+(b+c)…


In a discussion of C# this weekend, someone said (a+(b+c)) is the same as ((a+b)+c) when a,b,c are all primitive data types, like int, float, double, etc.


In pure math, sure.  In code, not necessarily. First consider System.Int32 and the following example test.cs:


using System;
class Program
{
    static void Main(string[] args)
    {
        int a = int.MaxValue;
        int b = 1;
        int c = -a;


        try { Console.WriteLine(a+(b+c)); }
        catch(Exception e) { Console.WriteLine(e.Message); }
  
        try { Console.WriteLine((a+b)+c); }
        catch(Exception e) { Console.WriteLine(e.Message); }
    }
}


Compile this with: csc.exe test.cs. Run test.exe, and you’ll get the output:


1
1


Makes sense.  Now compile it with: csc.exe /checked test.cs. Run test.exe, and you’ll get the output:


1
Arithmetic operation resulted in an overflow.


So order of operations does make a difference! Now consider an even more interesting example: floating-point numbers…


using System;
class Program
{
    static void Main(string[] args)
    {
        float a = float.MaxValue;
        float b = -a;
        float c = -1;


        Console.WriteLine(a+(b+c));
        Console.WriteLine((a+b)+c);
    }
}


Compile this with: csc.exe test.cs. Run test.exe, and you’ll get the output:


0
-1


So, while addition is generally associative in code, you might not always get the same results.  Something to at least be aware of.

Comments (7)

  1. What about when a == a is false? 🙂

    a = double.NaN

  2. Dan Wolf says:

    Take octonions for example… I believe there are other mathematical fields that are non-associative as well. Just a nit…

  3. Stephen Toub says:

    Good point, Dan. Thanks. I’ve clarified my comments.

  4. Matt Johnson says:

    Great post! It will drive my friend (a math wiz) nuts.

  5. florian cakolli says:

    a+(b+c) ist das gleiche wie a+b+c

  6. yyww says:

    Make non sense.