C#: Order of function evaluation (vs C)

后端 未结 8 1307
盖世英雄少女心
盖世英雄少女心 2020-12-19 07:01

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

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

The book says that since - and /

相关标签:
8条回答
  • 2020-12-19 07:36

    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.

    0 讨论(0)
  • 2020-12-19 07:38

    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.

    That's not quite correct. K&R allowed rearrangement of commutative operators (done away with in ANSI C). Since suibtraction is not commutative, it is not re-arrangeable...under that rule, at least.

    (Un)fortunately, C also doesn't define the order of evaluation (outside of a fairly small scope) - which means the compiler can call those functions in any order (as long as the result of pop() - pop() is fully evaluated before calling push())

    Which - in this case, results in the same problem - but for a different reason.

    0 讨论(0)
提交回复
热议问题