I have written a simple stack based virtual machine you can view it's source at https://github.com/radinParsaei/VM
when I compile it with clang it works well but if it compiles with GCC in bytecodes I have coded like pop() / pop()
it work irregular and it returns stack[stack.size() - 2] / stack[stack.size() - 1]
i fix this with writing that code like Value a = pop(); Value b = pop(); return a / b;
anyone has better idea?

- 28
- 1
- 6
-
[How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Jorengarenar Jul 12 '20 at 16:30
-
3Your problem probably stems from [order of evaluation](https://en.cppreference.com/w/cpp/language/eval_order) being unspecified for `operator /`. – IlCapitano Jul 12 '20 at 16:48
-
@IlCapitano I bet that you are right, and should make an answer from your comment. – Michael Veksler Jul 12 '20 at 18:06
-
@IlCapitano I couldn't find my answer in your comment I have achieved this result: g++ c.cpp ./a.out b() a() 5 clang++ c.cpp ./a.out b() a() 5 cat c.cpp #include
int a() { std::cout << "a()" << std::endl; return 2; } int b() { std::cout << "b()" << std::endl; return 10; } int main() { std::cout << b() / a() << std::endl; } – radinParsaei Jul 12 '20 at 18:12
1 Answers
As @IlCapitano says, your second pop()
may be called first:
There is no concept of left-to-right or right-to-left evaluation in C++. This is not to be confused with left-to-right and right-to-left associativity of operators: the expression a() + b() + c() is parsed as (a() + b()) + c() due to left-to-right associativity of operator+, but the function call to c may be evaluated first, last, or between a() or b() at run time
The key: the function call to c may be evaluated first, last, or between a() or b() at run time.
In response to comment:
order of evaluation is unspecified (with some exceptions). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.
So it depends on the compiler. Each does it differently.

- 2,526
- 1
- 13
- 17
-
Ok, but why clang's output is different from gcc? there are compile same programming language – radinParsaei Jul 12 '20 at 18:48
-
@radinParsaei GCC and clang are allowed to be different. One of them must have found a good reason to use a different order. Probably related to register allocation or stack slot ordering. – Zan Lynx Jul 12 '20 at 19:09