There is a stack implemented on the array. Why, when executing this code, we get the result "12", but if we write "cout" in different lines, then we get "21"? I would be very grateful for an explanation or article where you can read about it.

#include <iostream> using namespace std; struct stack { int size = 0; int st[1024]; }; void push(stack &st, int data) { if(st.size >= 1024) cout<< "Stack Overflow!\n"; else { st.st[st.size] = data;st.size++; } } int pop(stack &st) { if(st.size>=0) { --st.size; int data = st.st[st.size]; return data; } else cout<< "Stack Underflow!\n"; } int main() { stack mainstack; push(mainstack, 1); push(mainstack, 2); cout<< pop(mainstack)<<pop(mainstack); return 0; } 
  • Very strange. It should be the idea in both cases 21. Let me think ... - VladD
  • one
    ideone.com/9EAx9J the same garbage :) - user6550

1 answer 1

In this case, the order of calling pop() functions is not defined, they are not called from left to right, and since the compiler decides. In the same way, as in the expression f() + g() that f() called before g() or vice versa the standard does not say - everything is solved by the compiler. Calculation Order

  • Hmmm, it seems you are right. - VladD