I will try to explain in the way that I understand what is happening, if by chance I make a mistake in something correct me.
In the Ex1 for the multiplication of in a factor * (-num) it is necessary to evaluate first the values of the two operands, even if the precedence of multiplication(*) and pre-decrease(--) is the same, when the evaluation of the second operand is made in a will be decremented affecting the in a of the other operand, causing the multiplication to be made with the value of in a decremented.
For instructions that use more than one expression and the same variable more than once and its value is changed in one of the expressions this can cause undefined behaviors and lock the application, and this should be avoided, in these cases change the value of the variable before or after using it in these instructions.
In the Ex2 the expression num - 1 is evaluated forming a new value that will be copied to the function factorial, in a is not changed in this process, causing the multiplication to be carried out with the correct values.
OBS: In order for you to have executed this Ex1 code you should have the error flags of your compiler disabled, because when I went to test in g++ it did not even compile the code and issued the following error:
error: Operation on ːnum' may be Undefined [-Werror=Sequence-point]
Check and activate your compiler error flags, if you use g++ you can use the following flags:
-pedantic-errors -Wall -Weffc++ -Wextra -Wsign-Conversion -Werror
Try to answer: what is the value of
num
after making--num
? And after doingnum-1
?– Woss
The same value. I put a Cout<<num<Ndl before the if conditional, and tested both ways. The output was the same, with the exception of the factorial result. The factorial with num-1 the correct result and the factorial with --in a generates an almost certain result, since it gives me the factorial of the predecessor number, if I put in a = 5, gives me the factorial of 4 ie 24, and should have left 120... I do not know if I am explaining right
– ODA
That’s not what the colleague meant, it’s that
--num
changes the value ofnum
- and this occurs before it is multiplied by the result of the function.– bfavaretto
I think I got it
– ODA
So there’s no way, you have to put num -1 even, because if put -in a it will change the value of the variable and if put in a-- of the infinite loop, thank you both very much.
– ODA
This is explained here https://pt.cppreference.com/w/cpp/language/eval_order
– user72726