Order of Precedence (Order of Operation)

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"
using namespace std;

int main(){
	
        num = 7 - 4 + 2;
	cout << "Default direction: " << num << endl;
	
	num = 7 - (4+2);
	cout << "Forced direction: " << num << endl;
	
	_getch();
	return 0;
}
+ and - have the same precedence, and left to right associativity

[Edit]
I thought by the order of directional precedence (default) is that the computer or compiler does the addition first, and then the subtraction.

They have left to right associativity so the leftmost operator is evaluated first
Last edited on
What do you mean by left to right associativity? Does that mean the computer by default will do the subtraction first, followed by addition?
Addition and subtraction have the same precedence with a left to right association.

http://en.cppreference.com/w/cpp/language/operator_precedence
http://www.learncpp.com/cpp-tutorial/31-precedence-and-associativity/

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.
Last edited on
Okay, I got it. Thank you everyone for your response to my question,
Topic archived. No new replies allowed.