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:

OperatorNameExampleResult
+Additiona + bSum of a and b
-Subtractiona - bDifference of a and b
*Multiplicationa * bProduct of a and b
/Divisiona / bQuotient of a divided by b
%Moduloa % bRemainder 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):

OperatorNameExample
<Less thana < b
>Greater thana > b
<=Less than or equal toa <= b
>=Greater than or equal toa >= b
==Equal toa == b
!=Not equal toa != b
C. Logical Operators

These combine or modify relational expressions. They also return True (1) or False (0):

OperatorNameExampleResult (if a=1, b=0)
&&Logical ANDa && bTrue only if both a and b are True
||Logical ORa || bTrue if at least one of a or b is True
!Logical NOT!aInverts the logical state of a
D. Bitwise Operators

These operators work on individual bits of integers, commonly used in low-level programming:

OperatorNameExampleOperation
&Bitwise ANDA & BSets bit if corresponding bits in A and B are both 1.
|Bitwise ORA | BSets bit if at least one of the corresponding bits is 1.
^Bitwise XORA ^ BSets bit if corresponding bits are different.
~Bitwise NOT~AInverts all the bits of A (One’s Complement).
<<Left ShiftA << nShifts bits of A to the left by n positions.
>>Right ShiftA >> nShifts bits of A to the right by n positions.

2. Other Important Operators

E. Unary Operators

These operators work on a single operand:

OperatorNameExampleDescription
++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-aNegates the value of the operand.
sizeofSize ofsizeof(int)Returns the size, in bytes, of a variable or data type.
&Address-of&aReturns the memory address of the variable a.
*Dereference*pReturns 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
OperatorNamePurpose
,Comma OperatorUsed to separate expressions. Expressions are evaluated left-to-right; the entire expression takes the value of the rightmost expression.
( )ParenthesesUsed to group expressions (highest precedence) and in function calls.
[ ]BracketUsed 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+c is evaluated left-to-right).
Precedence LevelOperatorsAssociativity
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:

  1. Parentheses First: Expressions within the innermost parentheses are evaluated first.
  2. Precedence Rule: Higher precedence operators are evaluated before lower precedence ones (e.g., * and / before + and -).
  3. 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) becomes 5 + 8 - 2
  • Addition and Subtraction (Level 4, Left-to-Right):
    (5 + 8) - 2 becomes 13 - 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 (like float) 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.

StatementPurposeKey Feature
ifExecutes code if the condition is True.Simplest conditional structure.
if-elseExecutes one block if True, and an alternative block if False.Provides two-way branching.
Nested ifAn if statement inside another if or else.Used for multi-level condition checking.
else-if LadderChecks a series of conditions sequentially.Efficiently handles multiple, mutually exclusive conditions.
switch & breakMulti-way branch for a single variable against constant values.Uses case labels; break prevents “fall-through”.
gotoUnconditionally 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.

StatementStructureExecution GuaranteeWhen to Use
forfor (init; condition; update)Condition checked first.When the number of iterations is known.
whilewhile (condition)Condition checked first.When the number of iterations is unknown; loop runs as long as the condition is True.
do-whiledo { ... } 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).