Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Order of function evaluation (vs C)

Tags:

c

c#

math

Take the following C code (K&R pg. 77) :

push(pop() - pop()); /* WRONG */

The book says that since - and / are not commutative operators, the order in which the 2 pop functions are evaluated is necessary (obviously, to get the correct result)...and thus you have to put the result of the first function in a variable first and then proceed with the arithmetic, like such:

op2 = pop();
push(op2 - pop());

Apparently this is because the compiler can't guarantee in which order the functions are evaluated (...why?)


My question is, does C# do this same thing? as in, do I have to worry about this sort of thing when working with C# ? and for that matter, any of the other higher level languages ?

like image 290
Andreas Grech Avatar asked Jul 31 '09 22:07

Andreas Grech


Video Answer


3 Answers

In C# it is left to right: http://blogs.msdn.com/oldnewthing/archive/2007/08/14/4374222.aspx


Re: C++ order

Apparently this is because the compiler can't guarantee in which order the functions are evaluated (...why?)

Any particular compiler can guarantee the order. The problem is that the language spec does not specify an order, so each compiler can do whatever it wants. This means you have to add a sequence point between the two method calls if you want to guarantee ordering.

like image 69
Michael Donohue Avatar answered Sep 24 '22 11:09

Michael Donohue


To answer your question about why C doesn't define the order of operation, it's simply because the inventors of C decided it would be valuable to give compiler implementors the opportunity to optimize expression evaluation. They also decided that it was more valuable than giving programmers certainty in expression evaluation.

Remember that when C was originally developed, machines were much less capable than today, and there was more interest in giving compilers the optimization leeway. Today, there is often more weight given to safer, more predicatble code.

like image 21
Michael Burr Avatar answered Sep 23 '22 11:09

Michael Burr


From Fabulous Adventures In Coding: Precedence vs Associativity vs Order:

Another way to look at it is that the rule in C# is not "do the parentheses first", but rather to parenthesize everything then recursively apply the rule "evaluate the left side, then evaluate the right side, then perform the operation".

like image 38
Sam Harwell Avatar answered Sep 25 '22 11:09

Sam Harwell