Operators in C (Lesson)

Operators in C

Operators are symbols that tell the compiler to perform specific mathematical or logical manipulations.

5.1 Arithmetic Operators

Used for mathematical calculations.

OperatorDescriptionExample (a=10, b=3)
+Additiona + b = 13
-Subtractiona - b = 7
*Multiplicationa * b = 30
/Divisiona / b = 3 (int division)
%Modulus (Remainder)a % b = 1

5.2 Relational Operators

Used to compare two values. They return 1 (true) or 0 (false).

  • == (Equal to)
  • != (Not equal to)
  • > (Greater than)
  • < (Less than)
  • >= (Greater than or equal to)
  • <= (Less than or equal to)

5.3 Logical Operators

Used to combine multiple conditions.

  • && (Logical AND): True if both are true.
  • || (Logical OR): True if at least one is true.
  • ! (Logical NOT): Reverses the state.

5.4 Assignment Operators

Used to assign values to variables.

  • =: Simple assignment (a = b)
  • +=: Add and assign (a += b is a = a + b)
  • -=, *=, /=, %=: Similar behavior.

5.5 Increment and Decrement Operators

  • ++ (Increment): Increases value by 1.
    • Prefix (++a): Increment first, then use.
    • Postfix (a++): Use first, then increment.
  • -- (Decrement): Decreases value by 1.

5.6 Conditional (Ternary) Operator

The only operator in C that takes three operands. Syntax: condition ? expression1 : expression2;

int max = (a > b) ? a : b;

5.7 Bitwise Operators

Used for manipulation of data at the bit level.

  • & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left shift), >> (Right shift).

5.8 Special Operators

  • sizeof(): Returns the size of a data type in bytes.
  • & (Address-of): Returns the address of a variable.
  • * (Pointer-to): Pointer to a variable.

Example: Using Various Operators

#include <stdio.h>

int main() {
    int a = 10, b = 20, res;
    
    // Arithmetic
    printf("Addition: %d\n", a + b);
    
    // Logical
    if (a < b && a > 0) {
        printf("Condition is true\n");
    }
    
    // Ternary
    res = (a > b) ? a : b;
    printf("Higher value is %d\n", res);
    
    // Sizeof
    printf("Size of int: %lu bytes\n", sizeof(int));
    
    return 0;
}

Check the Lecture Slides for Operator Precedence and Associativity tables.

PREVIOUS
Elements of C
NEXT
5. Writing a Program in C