80 likes | 270 Views
Computer Programming CS F111. Vishal Gupta Department of Computer Science and Information Systems Birla Institute of Technology and Science Pilani Campus, Pilani . Agenda :. Expression Evaluation: Precedence & Associativity. Precedence and Associativity ?.
E N D
Computer ProgrammingCS F111 Vishal Gupta Department of Computer Science and Information Systems Birla Institute of Technology and Science Pilani Campus, Pilani
Agenda: Expression Evaluation: Precedence & Associativity
Precedence and Associativity? • Operators have rules that are used to determine how expressions are evaluated. • Precedence and associativity deal with the evaluation order within expressions. • Precedencerules specify the order in which operators of different precedence level are evaluated. • Associativityrules decides the order in which multiple occurrences of the same level operator are applied.
Rules of Evaluation of Expression • First, parenthesized sub expression from left to right are evaluated. • If parentheses are nested, the evaluation begins with the innermost sub expression. • The precedence rule is applied in determining the order of application of operators in evaluating sub-expressions. • The associativity rule is applied when two or more operators of the same precedence level appear in a sub expression.
Examples: Evaluate the following expressions 1) z = 2*3/4+4/4+8-2+5/7 z = ?? 2) y = 4/5*6+2/7+4 y = ?? 3) Let inta,b; float c,d; a=5;b=7; c=4.0;d=3.0; Then compute x = a/b*(c+d)/a-b+c/d
Example What is the output of the following piece of code ?? #include <stdio.h> int main (void) { int a, b=21, c=7; a = ++c – b-- % 5; printf (“Value of a = %d, b = %d, c = %d”,a, b, c); } Priority can be overruled by parenthesis. With this expression inside parenthesis are evaluated first so (1+2)*3 gives 9