Operators in C are special symbols that perform operations on variables and values. They enable arithmetic calculations, comparisons, logical decisions, and more in C programming.

Core Definition

An operator tells the compiler to execute specific mathematical or logical tasks on one or more operands (like numbers or variables). For instance, in 5 + 3, + is the operator acting on operands 5 and 3.

Operators classify by operand count:

  • Unary : One operand (e.g., ++i increments i).
  • Binary : Two operands (e.g., a + b).
  • Ternary : Three operands (e.g., condition ? true_value : false_value).

Types of Operators

C offers a rich set for diverse needs. Here's a breakdown with examples:

Arithmetic Operators

Handle basic math on numeric values.

OperatorDescriptionExample
+Addition or unary plus5 + 3 = 8
-Subtraction or unary minus5 - 3 = 2
*Multiplication5 * 3 = 15
/Division5 / 2 = 2
%Modulo (remainder)5 % 2 = 1
[1][7]

Relational Operators

Compare values, returning 1 (true) or 0 (false). Common in conditions.

OperatorDescriptionExample (10 > 5)
>Greater than1 (true)
<Less than0 (false)
>=Greater than or equal1 (true)
<=Less than or equal0 (false)
==Equal0 (false)
!=Not equal1 (true)
[5][7]

Logical Operators

Combine conditions (e.g., in if statements).

  • && (AND): True if both true (e.g., (5>3) && (10>2) = 1).
  • || (OR): True if at least one true.
  • ! (NOT): Reverses truth (e.g., !(5>3) = 0).

Other Key Types

  • Assignment : =, +=, -=, etc. (e.g., x += 5 means x = x + 5).
  • Increment/Decrement : ++ (pre/post-increment), --.
  • Bitwise : &, |, ^, ~, <<, >> for binary manipulation.
  • Ternary (?:) : Compact if-else.
  • Comma (,) : Evaluates multiple expressions, returns the last.
  • sizeof : Returns data type size (e.g., sizeof(int)).

Real-World Example

Imagine coding a simple calculator:

c

#include <stdio.h>
int main() {
    int a = 10, b = 5;
    printf("Addition: %d\n", a + b);  // 15
    printf("Equal? %d\n", a == b);   // 0 (false)
    printf("Logical AND: %d\n", (a > b) && (a != 0));  // 1
    return 0;
}

This outputs results using mixed operators, showing their power in expressions.

Common Pitfalls & Tips

  • Precedence : * before +; use parentheses for clarity (e.g., (a + b) * c).
  • Side Effects : i++ vs. ++i matters in complex expressions.
  • Integer Division : 5/2 = 2 (truncates); cast to float for decimals.

From forums like GeeksforGeeks, beginners often mix = (assign) with == (compare), causing bugs. Always test edge cases like zero division.

TL;DR: Operators power C's computations—from math to logic—with types like arithmetic (+, -) and relational ( >, ==). Master them via practice for bug- free code.

Information gathered from public forums or data available on the internet and portrayed here.