C documentation V1 Help

Operator Precedence

In C programming, operator precedence determines the order in which operators are evaluated in an expression. Knowing the precedence rules is crucial for writing code that behaves as expected. Let's explore the operator precedence in C and understand how it influences the execution of expressions.

Operator Precedence Rules

  1. Postfix operators: (), [], ., ->, ++, --

  2. Unary operators: +, -, !, ~, ++, --, sizeof, _Alignof

  3. Multiplicative operators: *, /, %

  4. Additive operators: +, -

  5. Shift operators: <<, >>

  6. Relational operators: <, <=, >, >=

  7. Equality operators: ==, !=

  8. Bitwise AND operator: &

  9. Bitwise XOR operator: ^

  10. Bitwise OR operator: |

  11. Logical AND operator: &&

  12. Logical OR operator: ||

  13. Conditional operator (ternary): ? :

  14. Assignment operators: =, +=, -=, *=, /=, %= etc.

  15. Comma operator: ,

Example

#include <stdio.h> int main() { int a = 5, b = 3, c = 7; // Example expression int result = a + b * c / 2 - (a % c); // Display the result printf("Result: %d\n", result); return 0; }

In this example, the expression a + b * c / 2 - (a % c) is evaluated based on operator precedence. Multiplication and division have higher precedence than addition and subtraction, and the modulus operation is performed in parentheses.

Practical Tips

  • Use parentheses to explicitly specify the order of evaluation when needed.

  • Understand the precedence to avoid unexpected behavior in complex expressions.

  • Refer to the operator precedence table for quick reference.

Understanding and applying operator precedence is fundamental for writing correct and predictable C code. If you have specific questions or if there are additional topics you'd like to explore, feel free to ask. Happy coding!

Last modified: 25 February 2024