Hi, can some explain to me why the default directional precedence in this line of code computes subtraction first, and then the addition? I thought by the order of directional precedence (default) is that the computer or compiler does the addition first, and then the subtraction.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include "conio.h"
usingnamespace std;
int main(){
num = 7 - 4 + 2;
cout << "Default direction: " << num << endl;
num = 7 - (4+2);
cout << "Forced direction: " << num << endl;
_getch();
return 0;
}
Parenthesis on the other hand has a much higher precedence and is done first (again parenthesis have a left to right association, not all operators do though so keep that in mind)
"associativity" really just means how to break a tie in precedence. So in 7 - 4 + 2
the operators have the same precedence, so which one will happen first? The answer is that the operator on the left has higher precedence, so we say it "associates left to right). In other words, the expression above is the same as (7 - 4) + 2
and 7 - 4 + 2 + 18 - 44 - 22 + 6
is evaluated as (((((7 - 4) + 2) + 18) - 44) - 22) + 6
If you had 7 + 4 - 2
addition would be first. It's just like in maths, with these operators. If you had 7 / 5 + 2 * 7
it would be equivalent to (7 / 5) + (2 * 7)
EDIT:
also remember you should specify type of variables, so don't write max = 5;, but int max = 5;. You have to specify it only once, at the beginning.