Here’s a concise, well-structured explanation of operator precedence and type casting in C:
Operator Precedence
Operator precedence determines the order in which operations are evaluated in expressions. This is critical for writing correct and readable code.
Key Rules
- Highest Precedence: Parentheses
()(override all rules) - Unary Operators:
!,~,-,+ - Multiplicative:
*,/,% - Additive:
+,- - Relational:
>,<,>=,<= - Equality:
==,!= - Logical AND:
&& - Logical OR:
|| - Ternary:
? :
Example
<code class="language-c">int result = 10 + 4 * 2; // 18 (not 28) <p>int result2 = (10 + 4) * 2; // 28</code>
Why It Matters
Parentheses are your most powerful tool to control evaluation order. Always use them to clarify intent in complex expressions.
Type Casting
Type casting converts values between different data types explicitly.
Syntax
<code class="language-c">(type) expression</code>
Common Cases
| Type Conversion | Example | Notes |
|---|---|---|
| Integer → Float | (float)7 |
7.0 (no rounding) |
| Float → Integer | (int)3.9 |
3 (truncates decimal) |
| Pointer Casting | (int*)malloc(...) |
Requires careful memory handling |
Critical Notes
- Truncation: Converting floats to integers truncates (not rounds)
- Overflow: Casting large values to smaller types causes undefined behavior
- Explicit vs Implicit:
- Implicit: int a = 5; float b = a; (safe)
- Explicit: float c = (float)a; (more precise control)
Example
<code class="language-c">float f = 3.9; <p>int int_val = (int)f; // 3 (truncates decimal)</p> <p>int x = 10;</p> <p>float y = (float)x; // 10.0 (explicit conversion)</code>
Key Takeaways
- Use parentheses to override default precedence and prevent errors
- Explicit casting gives precise control over type conversions
- Always check for truncation when converting floats to integers
- Avoid implicit conversions in complex expressions (use explicit casts)
💡 Pro Tip: When in doubt, add parentheses to your expressions. This is the single most effective way to avoid precedence errors in C.
This covers the essentials while maintaining clarity and practical relevance for real-world C programming.