Operators in C are essential tools for performing calculations, comparisons, and logical operations. Understanding these operators helps you manipulate data effectively, control program flow, and manage memory, laying the groundwork for more complex programming concepts.
-
*Arithmetic operators (+, -, , /, %)
- Used to perform basic mathematical operations: addition, subtraction, multiplication, division, and modulus.
- Division (/) of integers results in an integer (truncating any decimal).
- Modulus (%) returns the remainder of a division operation.
- Operator precedence determines the order of operations in expressions.
-
Assignment operator (=)
- Assigns the value on the right to the variable on the left.
- Can be combined with arithmetic operators (e.g., +=, -=) for shorthand assignments.
- The assignment operator evaluates the right-hand side expression before assigning it to the left.
-
Relational operators (==, !=, <, >, <=, >=)
- Used to compare two values or expressions.
- Returns a boolean value: true (1) or false (0).
- Commonly used in control flow statements (if, while) to make decisions based on conditions.
-
Logical operators (&&, ||, !)
- Used to combine or invert boolean expressions.
- Logical AND (&&) returns true if both operands are true.
- Logical OR (||) returns true if at least one operand is true.
- Logical NOT (!) inverts the truth value of an expression.
-
Increment and decrement operators (++, --)
- Increment (++) increases a variable's value by 1; decrement (--) decreases it by 1.
- Can be used in prefix (e.g., ++x) or postfix (e.g., x++) forms, affecting the order of evaluation.
- Commonly used in loops for iterating through values.
-
Bitwise operators (&, |, ^, ~, <<, >>)
- Operate on the binary representations of integers.
- Bitwise AND (&), OR (|), and XOR (^) perform operations on corresponding bits.
- Bitwise NOT (~) inverts all bits.
- Shift operators (<< for left shift, >> for right shift) move bits left or right, effectively multiplying or dividing by powers of two.
-
Conditional operator (? :)
-
Sizeof operator
- Returns the size (in bytes) of a data type or variable.
- Useful for memory management and understanding data storage requirements.
- Can be applied to types (e.g.,
sizeof(int)
) or variables (e.g., sizeof(variable)
).
-
Comma operator (,)
- Allows the evaluation of multiple expressions in a single statement.
- The value of the entire expression is the value of the last expression.
- Often used in for loops to initialize multiple variables.
-
Pointer operators ( and &)*
- The asterisk (*) is used to declare a pointer variable and to dereference a pointer to access the value it points to.
- The ampersand (&) is used to obtain the address of a variable.
- Essential for dynamic memory management and working with arrays and functions.