I am confused as to why would this result in an undefined behavior. Let me copy and paste the explanation from the textbook first and then show my own code and program which runs perfectly.
Precedence specifies how the operands are grouped. It says nothing about the order in which the operands are evaluated. In most cases, the order is largely unspecified. In the following expression*
int i = f1() * f2();
:
*We know thatf1
andf2
must be called before the multiplication can be done. After all, it is their results that are multiplied. However, we have no way of knowing whether f1 will be called before f2 or vice versa. For operators that do not specify evaluation order, it is an error for an expression to refer to and change the same object. Expressions that do so have undefined behavior (§ 2.1.2, p. 36). As a simple example, the << operator makes no guarantees about when or how its operands are evaluated. As a result, the following output expression is undefined.-- C++ Primer - Page 193 by Stanley B. Lippman
So, I tried to apply this by writing my own code and I never get an undefined behavior? Can someone please explain what does this mean?
#include <iostream>
using std::cout;
using std::endl;
int f1() { return (5 + 5 * 4 / 2 - 3); } // 12
int f2() { return (10 + 2 * 10 / 2 - 5); } // 15
int main()
{
int i = f1() * f2();
cout << i << endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire