Expression evaluation | datatypes, precedence, associativity

Notes:

Expression evaluation tables | Datatypes, precedence, associativity

I. Evaluating expressions : [Starts at:00min:00sec]
II. Evaluating expressions focusing on datatypes : [Starts at: 01min:43sec]
III. Evaluating expressions focusing on operators : [Starts at: 18min:41sec]

I. Evaluating expressions : [Starts at:00min:00sec]

What is an expression?:
Valid combination of operators and operands is called as an expression

Ex:
Valid expression: c = a + b
Invalid expression: c = + a = b
Where
+, = are operators
a, b, c are operands

Note:
While evaluating expressions we need to focus on: datatypes and operators

II. Evaluating expressions focusing on datatypes : [Starts at: 01min:43sec]

2 types of expressions based on data types:
a. Homogeneous: expression with similar types
9 / 2 = 4
int / int = int

b. Heterogeneous: expression with different types
9 / (float) 2 = 4.5
int / float = float

To evaluate expressions based on datatypes "Datatypes evaluation table" is used
Note:
Precision type wins
Largest size type wins

Example Code:
using UnityEngine;
public class OperatorsDemo : MonoBehaviour {
// Use this for initialization
void Start ()
{

Debug.Log (9 / 2); // 4 : Loss of data 0.5

// Solutions
Debug.Log((float)9/2); // 4.5
Debug.Log(9/(float)2); // 4.5
Debug.Log((float)9/(float)2); //4.5

// OR
Debug.Log(9.0f/2); // 4.5
Debug.Log(9/2.0f); // 4.5
Debug.Log(9.0f/2.0f); // 4.5

int a = 9, b = 2;

Debug.Log (a / b); // 4: Loss of data 0.5

// Solution
Debug.Log ((float)a / b);// 4.5

// largest type wins example
Debug.Log('A' + 5); // 70 : char + int = int
Debug.Log((char) ('A'+5)); // F

// Precision type wins
Debug.Log( 9 / 2.0f); // 4.5 : int / float = float
}
}

III. Evaluating expressions focusing on operators : [Starts at: 18min:41sec]

2 types of expressions based on operators:
a. Heterogeneous: expression with different operators
c = a + b
c = 2 + 3 precedence

Note:
When an expression contains different types of operators,
Precedence determines which operator should be evaluated before the other

b. Homogeneous: expression with similar operators
a + b + c
2 + 3 + 4 Associativity

Note:
When an expression contains similar types of operators,
Associativity determines the direction of evaluation
i.e. Left to right or Right to left or Inside out

To evaluate expressions based on Operators "Precedence & Associativity table" is used
Note:
Lower the precedence number higher the precedence

Example Code:
using UnityEngine;
public class OperatorsDemo : MonoBehaviour {
// Use this for initialization
void Start () {
// Precedence
Debug.Log (2 + 3 * 5); // 17 not 25
Debug.Log (2 * 3 + 8 / 2); // 10 not 7

// Associativity
Debug.Log (3 * 5 + 4 / 2 + 3); // 20
Debug.Log (3 * 9 / 2 + 3); // 16 not 16.5 loss of 0.5

//Solution
Debug.Log (3 * 9 / 2.0f + 3); // 16.5 correct result
}
}