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
Anonymous
February 28, 2005
What about when a == a is false? :-)
a = double.NaNAnonymous
February 28, 2005
The comment has been removedAnonymous
February 28, 2005
Good point, Dan. Thanks. I've clarified my comments.Anonymous
March 02, 2005
The comment has been removedAnonymous
September 15, 2009
a+(b+c) ist das gleiche wie a+b+cAnonymous
October 12, 2011
Make non sense.