Chapter Summary
This chapter explores how to use mathematical operators in C programs to perform calculations on data. Understanding operators and how they interact with different data types is essential because the results of calculations depend not only on the values being operated on, but also on the types of those values.
Key Concepts
-
Arithmetic Operators
- Basic Operators: Addition
+, subtraction-, multiplication*, division/, and modulus%perform standard mathematical operations - Integer vs. Floating-Point Division: When both operands are integers, division truncates (discards) the decimal portion rather than rounding. When at least one operand is floating-point, the result is floating-point
- Modulus Operator: The
%operator returns the remainder of integer division and only works with integer operands. It produces a repeating pattern useful for determining odd/even values and extracting digits
- Basic Operators: Addition
-
Operator Precedence
- Order of Operations: Multiplication, division, and modulus are evaluated before addition and subtraction (left to right within the same precedence level)
- Controlling Order: Parentheses override default precedence and make expressions clearer
-
Self-Assignment and Increment/Decrement Operators
- Self-Assignment: Operators like
+=,-=,*=,/=, and%=combine an operation and assignment into a single statement - Prefix vs. Postfix: Both
++x(prefix) andx++(postfix) increment the variable by 1, but prefix evaluates to the new value while postfix evaluates to the original value. This distinction matters when the result of the expression is used
- Self-Assignment: Operators like
-
Type Conversions in Calculations
- Promotion: When an integer and floating-point value are used together, the integer is automatically promoted to floating-point
- Casting: Use the syntax
(typename)expressionto intentionally convert types and signal to other programmers that the conversion is deliberate