C Operator Precedence and Associativity PDF

Summary

This document explains operator precedence and associativity in the C programming language. It provides examples and a table of operator precedence. It's a great resource for learning how expressions are evaluated in C.

Full Transcript

Operator Precedence and Associativity in C In C, when an expression contains multiple operators, operator precedence and associativity help decide which operations are performed first. Operator precedence determines the priority of operators in an expression. Associativity is us...

Operator Precedence and Associativity in C In C, when an expression contains multiple operators, operator precedence and associativity help decide which operations are performed first. Operator precedence determines the priority of operators in an expression. Associativity is used when two operators with the same precedence appear in an expression and determine the direction (left-to-right or right-to-left) in which they are evaluated. Example: Operator Precedence Let's evaluate: 10 + 20 * 30 Here, + (addition) and * (multiplication) are used. According to operator precedence, * has higher priority than +. Therefore, the expression is evaluated as: 10 + (20 * 30) // First multiplication 10 + 600 // Then addition 610 Example: Operator Associativity Associativity comes into play when operators with the same precedence appear, such as: 100 / 5 % 2 (L→R) Both / (division) and % (modulus) have the same precedence, so the order is determined by left-to-right associativity. Hence, the expression is evaluated as: (100 / 5) % 2 // First division 20 % 2 // Then modulus 0 Consider the expression: exp = 100 + 200 / 10 - 3 * 10 100+20-3*10 100+20-30 120-30 90 The / and * operators are evaluated first due to their higher precedence: exp = 100 + (200 / 10) - (3 * 10) = 100 + 20 - 30 = 90 Operator Precedence Table (From Highest to Lowest) The precedence and associativity of operators in C determine the order in which expressions are evaluated. The following table lists the operators in order of precedence, from highest to lowest, along with their associativity. Category Operator Associativity Postfix () [] ->. ++ - - Left to right + - ! ~ ++ - - Unary Right to left (type)* & sizeof Multiplicative */% Left to right Additive +- Left to right Shift > Left to right Relational < >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left = += -= *= /= Assignment %=>>=

Use Quizgecko on...
Browser
Browser