In C, operators are symbols used to perform operations on variables and values. They are a fundamental part of programming, enabling calculations, logical comparisons, and more.
Types of Operators in C
- Arithmetic Operators
- Used to perform basic mathematical operations.
- Operators:
+
(Addition),-
(Subtraction),*
(Multiplication),/
(Division),%
(Modulus).
Example:
- Relational Operators
- Used to compare values and return a Boolean result.
- Operators:
==
(Equal to),!=
(Not equal to),<
(Less than),>
(Greater than),<=
(Less than or equal to),>=
(Greater than or equal to).
Example:
- Logical Operators
- Used to perform logical operations on expressions.
- Operators:
&&
(Logical AND),||
(Logical OR),!
(Logical NOT).
Example:
- Bitwise Operators
- Used to perform operations at the bit level.
- Operators:
&
(Bitwise AND),|
(Bitwise OR),^
(Bitwise XOR),~
(Bitwise NOT),<<
(Left shift),>>
(Right shift).
Example:
- Assignment Operators
- Used to assign values to variables.
- Operators:
=
(Assign),+=
,-=
,*=
,/=
,%=
(Compound assignment).
Example:
- Unary Operators
- Operate on a single operand.
- Operators:
+
(Positive),-
(Negative),++
(Increment),--
(Decrement),!
(Logical NOT).
Example:
- Ternary Operator
- A shorthand for
if-else
. - Syntax:
condition ? value_if_true : value_if_false
Example:
- A shorthand for
- Special Operators
- Sizeof: Determines the size of a data type.
- Comma: Combines multiple expressions, evaluates from left to right.
- Pointer Operators:
*
(Dereference),&
(Address of).
Example:
Operator Precedence and Associativity
Operators have precedence that determines the order in which they are evaluated, and associativity determines the direction of evaluation (left-to-right or right-to-left).
Summary Table of Operators
Category | Operators | Example |
---|---|---|
Arithmetic | + , - , * , / , % |
a + b |
Relational | == , != , < , > , <= , >= |
a > b |
Logical | && , ` |
|
Bitwise | & , ` |
, ^, ~, <<, >>` |
Assignment | = , += , -= , *= , /= , %= |
a += b |
Unary | + , - , ++ , -- , ! |
++a |
Ternary | ? : |
a > b ? a : b |
Special | sizeof , , , * , & |
sizeof(a) |
Understanding operators is essential for building efficient and logical C programs.