#515 – Binary Operators Are Left-Associative

When an expression contains more than one binary operators, where the operators are identical or have the same precedence, the operators are left-assocative.  This means that the expression is evaluated from left to right.

For example, the result of the expression shown below is 5, rather than 20.  80 is divided by 8 to get an intermediate result of 10.  10 is then divided by 2 to get a result of 5.

            double result = 80 / 8 / 2;

This means that the above expression is equivalent to:

            double result = (80 / 8) / 2;

If you want to force the division of the 2nd and 3rd operands to happen first, you could use parentheses around them:

            // result = 20
            double result = 80 / (8 / 2);

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #515 – Binary Operators Are Left-Associative

  1. Pingback: #1,074 – Use Parentheses in Expressions to Make Code More Readable | 2,000 Things You Should Know About C#

  2. Pingback: #1,075 – Operator Precedence Doesn’t Affect Operand Evaluation Order | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: