C#: Order of function evaluation (vs C)

后端 未结 8 1316
盖世英雄少女心
盖世英雄少女心 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:32

    No, C# doesn't do the same thing. It doesn't use evaluation boundaries the same way as C does, where the order of execution between the boundaries is undefined. The expression is evaluated left to right, just as you would expect.

    If you are ever uncertain of the order of execution, or if you want to make the code clearer, you should use a local variable for an intermediate result. Local variables are very cheap to allocate as they are allocated on the stack, and in some cases the compiler is even able to put the variable in a register so that it's not allocated at all. Besides, depending on how the expression looks the compiler may need to use a local variable to store the intermediade result anyway.

提交回复
热议问题