Behavior and evaluation order in C #

Possible duplicate:
C #: Function Evaluation Order (vs C)

Code snippet:

i += ++i; a[++i] = i; int result = fun() - gun(); //statement of similar kind 

Are their behavior correct in C #? In C ++, such code causes undefined / unspecified behavior . Please also indicate the relevant sections from the language specification in your answer!

+3
undefined-behavior order-of-evaluation c #
source share
2 answers

The key here is the table in "1.4 expressions" and "7.3.1 operator precedence and associativity." I will not duplicate the table from 1.4, but to indicate 7.3.1:

  • With the exception of assignment operators, all binary operators are left-associative, which means that operations are performed from left to right correctly. For example, x + y + z is evaluated as (x + y) + z.
  • assignment operators and a conditional operator (? :) are right-associative, which means that operations are performed with left. For example, x = y = z is evaluated as x = (y = z).

The first is logically expanded (or: uses the rules of associativity) as:

 i = i + ++i; 

here the order (from the table) is a preliminary increment, then an addition, then an assignment - so we should expect me to double plus one. And indeed, with i=6 we get 13 as expected.

 a[++i] = i; 

again from the table, the order should be access to the array, pre-increment, assignment - so I would expect that I + 1'th value would be me + 1. And really, check:

  int[] a = { 0, 0, 0, 0, 0 }; int i = 2; a[++i] = i; 

we really get {0, 0, 0, 3, 0} .

At the last method call, it takes precedence over subtraction, then it is from left to right; therefore it should be fun() , gun() , - , assignment.

+9
source share

People are always so confused that it's sad because in C # it is very simple. Rules:

  • subexpressions are observed for evaluation from left to right when they are observed from an executable stream, period, end of story. (The rating order is allowed to be noticed by any other thread if any other thread is observing side effects.)

  • the order in which the statements are executed is determined by their priority and associativity.

These are just two relevant rules, and they completely determine the behavior of the code you give. IN

 i += ++i; 

i is first evaluated, then ++ i is calculated, and then + = is performed.

 a[++i] = i; 

First, "a" is evaluated, then ++ i is calculated, then the indexing operator is executed, then i is evaluated, then the assignment is performed.

 int result = fun() - gun(); 

first result is evaluated, then fun, then gun, then subtraction, then assignment.

Please also indicate the relevant sections from the language specification in your answer!

You can look very well in the table of contents. Find it is not difficult.

+10
source share

All Articles