C Language Operators, Expressions, and Control Flow
C Operators and Expressions Fundamentals
Understanding C operators and expressions is crucial. This section details the different types of operators, their hierarchy, and expression evaluation rules.
Operators and Expressions Defined
An operator is a symbol that instructs the compiler to perform specific mathematical or logical manipulations. An expression is a combination of operators, constants, and variables that resolves to a single value.
1. Primary Operator Types
A. Arithmetic Operators
These are used to perform mathematical calculations:
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | a + b | Sum of a and b |
- | Subtraction | a - b | Difference of a and b |
* | Multiplication | a * b | Product of a and b |
/ | Division | a / b | Quotient of a divided by b |
% | Modulo | a % b | Remainder of a divided by b (integers only) |
B. Relational Operators
These operators compare two values and return a Boolean result (1 for True, 0 for False):
| Operator | Name | Example |
|---|---|---|
< | Less than | a < b |
> | Greater than | a > b |
<= | Less than or equal to | a <= b |
>= | Greater than or equal to | a >= b |
== | Equal to | a == b |
!= | Not equal to | a != b |
C. Logical Operators
These combine or modify relational expressions. They also return True (1) or False (0):
| Operator | Name | Example | Result (if a=1, b=0) |
|---|---|---|---|
&& | Logical AND | a && b | True only if both a and b are True |
|| | Logical OR | a || b | True if at least one of a or b is True |
! | Logical NOT | !a | Inverts the logical state of a |
D. Bitwise Operators
These operators work on individual bits of integers, commonly used in low-level programming:
| Operator | Name | Example | Operation |
|---|---|---|---|
& | Bitwise AND | A & B | Sets bit if corresponding bits in A and B are both 1. |
| | Bitwise OR | A | B | Sets bit if at least one of the corresponding bits is 1. |
^ | Bitwise XOR | A ^ B | Sets bit if corresponding bits are different. |
~ | Bitwise NOT | ~A | Inverts all the bits of A (One’s Complement). |
<< | Left Shift | A << n | Shifts bits of A to the left by n positions. |
>> | Right Shift | A >> n | Shifts bits of A to the right by n positions. |
2. Other Important Operators
E. Unary Operators
These operators work on a single operand:
| Operator | Name | Example | Description |
|---|---|---|---|
++ | Increment | ++a or a++ | Increases the value of the operand by 1. |
-- | Decrement | --a or a-- | Decreases the value of the operand by 1. |
- | Unary Minus | -a | Negates the value of the operand. |
sizeof | Size of | sizeof(int) | Returns the size, in bytes, of a variable or data type. |
& | Address-of | &a | Returns the memory address of the variable a. |
* | Dereference | *p | Returns the value located at the address stored in the pointer p. |
- Prefix (
++a): Increments before the expression is evaluated. - Postfix (
a++): Increments after the expression is evaluated.
F. Assignment Operator
The simple assignment operator is =. C also supports compound assignment operators like +=, -=, *=, /=, etc.
G. Conditional Operator (?:)
This is C’s only ternary operator (takes three operands). It is a shorthand for a simple if-else statement.
Syntax:condition ? expression_if_true : expression_if_false;
Example:int x = 10, y = 5;
int max = (x > y) ? x : y; // max will be 10
H. Special Operators
| Operator | Name | Purpose |
|---|---|---|
, | Comma Operator | Used to separate expressions. Expressions are evaluated left-to-right; the entire expression takes the value of the rightmost expression. |
( ) | Parentheses | Used to group expressions (highest precedence) and in function calls. |
[ ] | Bracket | Used for array indexing. |
3. Operator Hierarchy (Precedence and Associativity)
When an expression has multiple operators, the hierarchy determines the evaluation order.
- Precedence: Dictates which operator is evaluated first (e.g.,
*has higher precedence than+). - Associativity: Dictates the direction (left-to-right or right-to-left) of evaluation when two operators have the same precedence (e.g.,
a+b+cis evaluated left-to-right).
| Precedence Level | Operators | Associativity |
|---|---|---|
| 1 (Highest) | ( ) [ ] . -> ++ (post) -- (post) | Left to Right |
| 2 | ++ (pre) -- (pre) ! ~ + (unary) - (unary) & (addr) * (deref) sizeof (Type Cast) | Right to Left |
| 3 | * / % (Multiplicative) | Left to Right |
| 4 | + - (Additive) | Left to Right |
| 5 | << >> (Shift) | Left to Right |
| 6 | < <= > >= (Relational) | Left to Right |
| 7 | == != (Equality) | Left to Right |
| 8 | & (Bitwise AND) | Left to Right |
| 9 | ^ (Bitwise XOR) | Left to Right |
| 10 | | (Bitwise OR) | Left to Right |
| 11 | && (Logical AND) | Left to Right |
| 12 | || (Logical OR) | Left to Right |
| 13 | ?: (Conditional) | Right to Left |
| 14 (Lowest) | = += -= *= /= etc. (Assignment) | Right to Left |
4. Evaluation of Arithmetic Expressions
An arithmetic expression results in a numerical value. Examples include A * B - C or (x + y) / 2.
Evaluation Process
Evaluation is strictly governed by Precedence and Associativity rules:
- Parentheses First: Expressions within the innermost parentheses are evaluated first.
- Precedence Rule: Higher precedence operators are evaluated before lower precedence ones (e.g.,
*and/before+and-). - Associativity Rule: If operators have the same precedence, evaluation proceeds based on associativity (usually Left-to-Right for arithmetic).
Example: Evaluate A + B * C - D / E
Assume A=5, B=2, C=4, D=6, E=3.
- Multiplication and Division (Level 3):
5 + (2 * 4) - (6 / 3)becomes5 + 8 - 2 - Addition and Subtraction (Level 4, Left-to-Right):
(5 + 8) - 2becomes13 - 2 - Final Subtraction:
Result:11
Understanding this hierarchy is vital to predicting the outcome of any C expression.
Type Conversion, Decision Making, and Looping
🔄 Type Conversion and Casting
Type Conversion changes a variable’s data type.
- Implicit Conversion (Coercion): Done automatically by the compiler, usually promoting a smaller type (like
int) to a larger type (likefloat) to avoid data loss. - Explicit Conversion (Type Casting): Done manually by the programmer using the syntax
(data_type) expression;to force a specific conversion, often to ensure floating-point division when working with integers.
⚙️ Decision Making Statements
These statements execute code blocks based on a condition’s truth value.
| Statement | Purpose | Key Feature |
|---|---|---|
if | Executes code if the condition is True. | Simplest conditional structure. |
if-else | Executes one block if True, and an alternative block if False. | Provides two-way branching. |
Nested if | An if statement inside another if or else. | Used for multi-level condition checking. |
else-if Ladder | Checks a series of conditions sequentially. | Efficiently handles multiple, mutually exclusive conditions. |
switch & break | Multi-way branch for a single variable against constant values. | Uses case labels; break prevents “fall-through”. |
goto | Unconditionally transfers control to a labeled point in the function. | Generally discouraged due to creating difficult-to-follow code. |
🔁 Looping Statements
These statements allow a block of code to be executed repeatedly until a termination condition is met.
| Statement | Structure | Execution Guarantee | When to Use |
|---|---|---|---|
for | for (init; condition; update) | Condition checked first. | When the number of iterations is known. |
while | while (condition) | Condition checked first. | When the number of iterations is unknown; loop runs as long as the condition is True. |
do-while | do { ... } while (condition); | Loop body executes at least once. | When the loop must run once before checking the condition. |
Jumps in Loops
break: Terminates the innermost loop immediately, resuming execution at the statement after the loop.continue: Skips the rest of the current loop iteration and proceeds directly to the next iteration (re-evaluating the condition).
