what is operator in c language
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.,
++iincrements 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.
| Operator | Description | Example |
|---|---|---|
| + | Addition or unary plus | 5 + 3 = 8 |
| - | Subtraction or unary minus | 5 - 3 = 2 |
| * | Multiplication | 5 * 3 = 15 |
| / | Division | 5 / 2 = 2 |
| % | Modulo (remainder) | 5 % 2 = 1 |
Relational Operators
Compare values, returning 1 (true) or 0 (false). Common in conditions.
| Operator | Description | Example (10 > 5) |
|---|---|---|
| > | Greater than | 1 (true) |
| < | Less than | 0 (false) |
| >= | Greater than or equal | 1 (true) |
| <= | Less than or equal | 0 (false) |
| == | Equal | 0 (false) |
| != | Not equal | 1 (true) |
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 += 5meansx = 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.++imatters 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.