Post

Operators in C

Operators in C

C Operators – Complete Guide

1. Arithmetic Operators

Arithmetic operators perform basic mathematical calculations.

OperatorNameDescriptionExample
+AdditionAdds two valuesx + y
-SubtractionSubtracts one value from anotherx - y
*MultiplicationMultiplies two valuesx * y
/DivisionDivides one value by anotherx / y
%ModulusRemainder of divisionx % y
++IncrementIncreases variable by 1 (Pre/Post)++x / x++
--DecrementDecreases variable by 1 (Pre/Post)--x / x--

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>

int main() {
    int x = 10, y = 3;

    printf("Addition: %d\n", x + y);
    printf("Subtraction: %d\n", x - y);
    printf("Multiplication: %d\n", x * y);
    printf("Division: %d\n", x / y);  // Integer division
    printf("Modulus: %d\n", x % y);

    x++; // Increment
    printf("Incremented x: %d\n", x);

    y--; // Decrement
    printf("Decremented y: %d\n", y);

    return 0;
}

2. Assignment & Augmented Assignment Operators

Used to assign values to variables. Augmented assignment combines assignment with an operation.

OperatorExampleEquivalent ToDescription
=x = 5x = 5Assigns value
+=x += 3x = x + 3Adds and assigns
-=x -= 3x = x - 3Subtracts and assigns
*=x *= 3x = x * 3Multiplies and assigns
/=x /= 3x = x / 3Divides and assigns
%=x %= 3x = x % 3Modulus and assigns
&=x &= 3x = x & 3Bitwise AND and assigns
\|=x \|= 3x = x \| 3Bitwise OR and assigns
^=x ^= 3x = x ^ 3Bitwise XOR and assigns
>>=x >>= 3x = x >> 3Right shift and assign
<<=x <<= 3x = x << 3Left shift and assign

Example:

1
2
3
4
5
6
7
8
#include <stdio.h>

int main() {
    int x = 10;
    x += 5; // x = x + 5
    printf("Updated x: %d\n", x); // Output: 15
    return 0;
}

3. Comparison Operators

Compare two values and return 1 (true) or 0 (false).

OperatorNameExampleDescription
==Equal tox == yTrue if equal
!=Not equalx != yTrue if not equal
>Greater thanx > yTrue if left is greater
<Less thanx < yTrue if left is less
>=Greater or equal tox >= yTrue if greater or equal
<=Less or equal tox <= yTrue if less or equal

Example:

1
2
3
4
5
6
7
8
#include <stdio.h>

int main() {
    int x = 5, y = 3;
    printf("x > y: %d\n", x > y); // 1 (true)
    printf("x < y: %d\n", x < y); // 0 (false)
    return 0;
}

4. Logical Operators

Used to combine conditions.

OperatorNameExampleDescription
&&ANDx < 5 && y > 2True if both conditions are true
\|\|ORx < 5 \|\| y > 5True if at least one condition is true
!NOT!(x == y)Reverses the result

Example:

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main() {
    int x = 4, y = 6;

    printf("(x < 5 && y > 5): %d\n", (x < 5 && y > 5)); // 1
    printf("(x > 5 || y > 5): %d\n", (x > 5 || y > 5)); // 1
    printf("!(x == 4): %d\n", !(x == 4));               // 0

    return 0;
}
This post is licensed under CC BY 4.0 by the author.