Types of Operators in C: Explained with Examples (2026)
By Rohan Vats
Updated on Dec 05, 2025 | 28 min read | 73.99K+ views
Share:
Working professionals
Fresh graduates
More
By Rohan Vats
Updated on Dec 05, 2025 | 28 min read | 73.99K+ views
Share:
Table of Contents
The C programming language utilizes various types of operators to perform operations on data. These operators can be categorized as Arithmetic, Relational, Logical, Bitwise, Assignment, and Conditional operators. Mastering these symbols is critical for manipulating data at the bit level and ensuring efficient memory management.
In this guide, you’ll read more about the specific functions and syntax of every operator category. We will break down types of operators in C with real-world coding examples.
Want to take charge of your data science journey? Join our Data Science Courses and step into the industry with confidence!
Operators are symbols or keywords that tell you to carry out specific actions. For example, in the 'a + b' expression, the '+' operator directs the system to add the two operands, a and b. Operands can be variables, constants, or even entire expressions.
Below is a brief table showing the major types of opreators :
Types of Operators |
Usage |
Few Example Symbols |
| Arithmetic | Performs basic math such as addition, subtraction, multiplication |
|
| Assignment | Assigns or updates variable values |
|
| Relational | Compares values and returns a truth value |
|
| Logical | Combines multiple conditions or inverts them |
|
| Bitwise | Works directly on the binary representation of integers |
|
| Special | Covers unique tasks like size checking, pointer access, and more |
|
When analyzing the operators in C language, we generally classify them into six distinct categories based on their functionality. Understanding these different types of operators is crucial because choosing the right one directly impacts the memory efficiency and speed of your application.
Arithmetic operators are likely the first types of operators in C you will encounter. They perform standard mathematical calculations such as addition (+), subtraction (-), multiplication (*), and division (/). Additionally, the modulus operator (%) is uniquely useful in programming for finding remainders. These operators in C language form the building blocks for logic involving counters, loops, and complex mathematical algorithms.
Here are the 9 types of arithmetic operators in C:
Symbol & Name |
Purpose |
Syntax* |
| + (Addition) | Adds two operands | result = a + b; |
| - (Subtraction) | Subtracts right operand from left operand | result = a - b; |
| * (Multiplication) | Multiplies two operands | result = a * b; |
| / (Division) | Divides left operand by right operand | result = a / b; |
| % (Modulus) | Returns remainder after division | result = a % b; |
| ++ (Increment) | Adds 1 to the operand | ++a; or a++; |
| -- (Decrement) | Subtracts 1 from the operand | --a; or a--; |
| + (Unary Plus) | Indicates a positive value | +a; |
| - (Unary Minus) | Negates the operand | -a; |
Please Note: In C, each statement ends with a semicolon (;). It’s simply a statement terminator that tells the compiler, “This line of code ends here.” For instance, when you write result = a + b;, the semicolon indicates that this assignment statement is complete.
Example of Arithmetic Operators in C
This sample program shows how to add, multiply, and find remainders, along with incrementing and decrementing variables. By observing how each operator modifies the values of ‘x’ and ‘y’, you can see how arithmetic operators streamline calculations in a straightforward way.
#include <stdio.h>
int main() {
int a = 10, b = 3;
// Unary Plus and Unary Minus
int positiveA = +a;
int negativeA = -a;
// Basic Arithmetic
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
// Increment and Decrement
a++;
b--;
printf("Unary plus of a: %d\n", positiveA);
printf("Unary minus of a: %d\n", negativeA);
printf("Sum (a + b): %d\n", sum);
printf("Difference (a - b): %d\n", difference);
printf("Product (a * b): %d\n", product);
printf("Quotient (a / b): %d\n", quotient);
printf("Remainder (a %% b): %d\n", remainder);
printf("After Increment, a: %d\n", a);
printf("After Decrement, b: %d\n", b);
return 0;
}
Output:
Unary plus of a: 10
Unary minus of a: -10
Sum (a + b): 13
Difference (a - b): 7
Product (a * b): 30
Quotient (a / b): 3
Remainder (a % b): 1
After Increment, a: 11
After Decrement, b: 2
Real-World Uses of Arithmetic Operators
Use Case |
Common Scenario |
Operators in Action |
| Financial Calculations | Calculating totals, discounts, or interest in billing systems. | +, -, *, / |
| Gaming Mechanics | Tallying scores, tracking lives, or updating player stats. | ++ for counters, += for scores |
| Data Analysis | Summing arrays, averaging values, or finding remainders. | +, /, % |
| Loops and Iterations | Incrementing or decrementing loop variables. | ++, -- |
| Geometry and Trigonometry | Computing areas, perimeters, or angles in real-time. | *, /, % (for specific needs) |
Also Read: What is Array in C? With Examples
Assignment operators in C help you store or update the value of a variable. The most basic form is =, which assigns the right-hand value to the left-hand variable. Beyond that, compound assignment operators like += or -= combine arithmetic and assignment in one step. This can reduce code repetition and make expressions more concise.
Below is a look at all the 11 assignment operator types you might encounter in the C programming language.
Symbol & Name |
What It Does |
Syntax |
| = (Simple Assignment) | Places the right-hand value into the left-hand variable. | a = b; |
| += (Add and Assign) | Adds the right-hand value to the variable, then stores the sum in that variable. | a += b; |
| -= (Subtract and Assign) | Subtracts the right-hand value from the variable, then stores the result. | a -= b; |
| *= (Multiply and Assign) | Multiplies the variable by the right-hand value, then stores the result. | a *= b; |
| /= (Divide and Assign) | Divides the variable by the right-hand value, then stores the result. | a /= b; |
| %= (Modulus and Assign) | Performs modulus with the right-hand value, then stores the remainder. | a %= b; |
| <<= (Left Shift and Assign) | Shifts bits to the left, then stores the shifted value. | a <<= b; |
| >>= (Right Shift and Assign) | Shifts bits to the right, then stores the shifted value. | a >>= b; |
| &= (Bitwise AND and Assign) | Performs a bitwise AND, then stores the result. | a &= b; |
| |= (Bitwise OR and Assign) | Performs a bitwise OR, then stores the result. | a |= b; |
| ^= (Bitwise XOR and Assign) | Performs a bitwise XOR, then stores the result. | a ^= b; |
Example of Assignment Operators in C
The following program shows all 11 types of assignment operators in action. You’ll see how they modify a variable’s value step by step, including simple arithmetic and bitwise changes.
#include <stdio.h>
int main() {
int a = 10, b = 3;
// Simple Assignment
printf("Initial value of a: %d\n", a);
// Add and Assign
a += b; // a = a + b
printf("After a += b, a: %d\n", a);
// Subtract and Assign
a -= b; // a = a - b
printf("After a -= b, a: %d\n", a);
// Multiply and Assign
a *= b; // a = a * b
printf("After a *= b, a: %d\n", a);
// Divide and Assign
a /= b; // a = a / b
printf("After a /= b, a: %d\n", a);
// Modulus and Assign
a %= b; // a = a % b
printf("After a %%= b, a: %d\n", a);
// Reset a to 10 for bitwise operations
a = 10;
// Left Shift and Assign
a <<= 1; // a = a << 1
printf("After a <<= 1, a: %d\n", a);
// Right Shift and Assign
a >>= 1; // a = a >> 1
printf("After a >>= 1, a: %d\n", a);
// Reset a to 10 for bitwise AND
a = 10;
a &= b; // a = a & b
printf("After a &= b, a: %d\n", a);
// Reset a to 10 for bitwise OR
a = 10;
a |= b; // a = a | b
printf("After a |= b, a: %d\n", a);
// Reset a to 10 for bitwise XOR
a = 10;
a ^= b; // a = a ^ b
printf("After a ^= b, a: %d\n", a);
return 0;
}
Output:
Initial value of a: 10
After a += b, a: 13
After a -= b, a: 10
After a *= b, a: 30
After a /= b, a: 10
After a %= b, a: 1
After a <<= 1, a: 20
After a >>= 1, a: 10
After a &= b, a: 2
After a |= b, a: 11
After a ^= b, a: 9
Real-World Uses of Assignment Operators
Use Case |
Typical Scenario |
Operators in Action |
| Updating Counters | Keeping track of loop iterations or counts in programs | a += 1; or a -= 1; |
| Accumulating Totals | Maintaining running sums or aggregates | total += newValue; |
| Bitwise Flags | Managing status bits (e.g., feature toggles) | `flags |
| Modifying Large Arrays | Scaling or adjusting array elements in numeric projects | array[i] *= scaleFactor; |
| Networking Protocols | Shifting and masking bits for data packet handling | header <<= 1; header &= mask; |
Relational operators are essential for decision-making. Among the various types of operators in C, these are used to compare two values, returning either true (1) or false (0). Common symbols include == (equal to), != (not equal), and > (greater than). Mastery of these operators in C language is mandatory for controlling the flow of your program using conditional statements like if and while loops.
Here’s an overview of all the 6 types of relational operators in C:
Symbol & Name |
What It Does |
Syntax |
| < (Less Than) | Returns 1 if left operand is smaller than right | result = a < b; |
| > (Greater Than) | Returns 1 if left operand is larger than right | result = a > b; |
| <= (Less or Equal) | Returns 1 if left operand is smaller or equal to right | result = a <= b; |
| >= (Greater or Equal) | Returns 1 if left operand is larger or equal to right | result = a >= b; |
| == (Equal To) | Returns 1 if both operands have the same value | result = a == b; |
| != (Not Equal To) | Returns 1 if both operands have different values | result = a != b; |
Example of Relational Operators in C
The following program checks various conditions on two integers and prints whether those conditions are true or false. This helps illustrate how each relational operator can be used for comparisons in everyday coding tasks.
#include <stdio.h>
int main() {
int x = 10, y = 3;
printf("x < y : %d\n", x < y);
printf("x > y : %d\n", x > y);
printf("x <= y : %d\n", x <= y);
printf("x >= y : %d\n", x >= y);
printf("x == y : %d\n", x == y);
printf("x != y : %d\n", x != y);
return 0;
}
Output:
x < y : 0
x > y : 1
x <= y : 0
x >= y : 1
x == y : 0
x != y : 1
Real-World Uses of Relational Operators
Use Case |
Typical Scenario |
Operators in Action |
| Validation Checks | Ensuring a user’s age is above a certain limit | if (age >= 18) |
| Loop Conditions | Running a loop until a value exceeds a threshold | while (count < limit) |
| Sorting Algorithms | Comparing elements for sorting in ascending or descending order | if (arr[i] > arr[j]) |
| Exam Scoring | Checking if a student’s marks meet the pass mark | if (marks >= passMark) |
| Inventory Thresholds | Triggering alerts if stock falls below a reorder level | if (stock <= minReq) |
You can also check out upGrad’s tutorial, ‘For Loop in C’. Discover how the loop works, its types, syntax, and more.
Logical operators in C let you combine or invert multiple conditions in a single expression.
These types of operators in C are essential in loops, conditional statements, and error-handling routines because they give you greater control over the flow of your program. They also help you write clearer, more readable conditions instead of nesting numerous if-else blocks.
Here are the 3 types of logical operators in C:
Symbol & Name |
What It Does |
Syntax |
| && (Logical AND) | Returns 1 if both conditions are true, else 0 | result = condition1 && condition2; |
| || (Logical OR) | Returns 1 if at least one condition is true, else 0 | result = condition1 || condition2; |
| ! (Logical NOT) | Reverses a condition’s value: true becomes false, and vice versa | result = !condition; |
Example of Logical Operators in C
The following program shows how each logical operator works by evaluating conditions on two integers. You’ll see how combining checks can simplify decision-making and reduce multiple nested if statements.
#include <stdio.h>
int main() {
int x = 5, y = 10;
// Logical AND
printf("x < 10 && y > 5 : %d\n", (x < 10) && (y > 5));
// Logical OR
printf("x > 10 || y == 10: %d\n", (x > 10) || (y == 10));
// Logical NOT
printf("!(x < y) : %d\n", !(x < y));
return 0;
}
Output:
x < 10 && y > 5 : 1
x > 10 || y == 10: 1
!(x < y) : 0
Real-World Uses of Logical Operators
Use Case |
Typical Scenario |
Operators in Action |
| Form Validation | Checking multiple fields (e.g., name not empty and age valid) | (nameNotEmpty && ageValid) |
| Search Filters | Displaying results that match any of several criteria | (color == "Red") || (size == 'M') || (brand == "Nike") |
| Loop Conditions | Continuing a loop only if multiple conditions stay true | while (count < max && balance > 0) |
| Error Handling | Inverting error flags to simplify logic | if (!errorFlag) |
| Feature Toggles | Combining flags to enable or disable certain features | if (isBetaUser && !isFeatureLocked) |
Bitwise operators work directly on the binary representation of data, making them unique among the types of operators in C. They include operations like AND (&), OR (|), XOR (^), and Bit Shift (<<, >>). Because C is often used for system-level programming, these operators in C language are critical for tasks requiring hardware manipulation, data compression, and setting specific "flags" in memory-constrained environments.
Here are the 6 types of Bitwise operators explained:
Symbol & Name |
What It Does |
Syntax |
| & (Bitwise AND) | Compares each bit of two operands and returns 1 if both bits are 1 | result = a & b; |
| | (Bitwise OR) | Returns 1 for each bit position where at least one operand has a 1 | result = a | b; |
| ^ (Bitwise XOR) | Returns 1 for each bit position where bits differ between the two operands | result = a ^ b; |
| ~ (Bitwise NOT) | Flips every bit of the operand | result = ~a; |
| << (Left Shift) | Moves bits to the left by the specified amount, filling vacant bits with 0 | result = a << b; |
| >> (Right Shift) | Moves bits to the right by the specified amount, filling vacant bits with 0 (in most compilers) | result = a >> b; |
Example of Bitwise Operators in C
The following code demonstrates how bitwise operations in C affect the binary representation of two integers. You can see how each operator changes the bits, which is critical for tasks like flag management or fast calculations in embedded programming.
#include <stdio.h>
int main() {
int x = 5, y = 3; // In binary: x = 0101, y = 0011
printf("x & y: %d\n", x & y);
printf("x | y: %d\n", x | y);
printf("x ^ y: %d\n", x ^ y);
printf("~x : %d\n", ~x);
printf("x << 1: %d\n", x << 1);
printf("x >> 1: %d\n", x >> 1);
return 0;
}
Output:
x & y: 1
x | y: 7
x ^ y: 6
~x : -6
x << 1: 10
x >> 1: 2
Real-World Uses of Bitwise Operators
Use Case |
Typical Scenario |
Operators in Action |
| Encryption | Performing XOR-based operations on data | encrypted = plain ^ key; |
| Checksum | Calculating simple checks by shifting and combining bits | checksum ^= data << shift; |
| Graphics | Manipulating pixel data at the bit level | pixelValue & colorMask; |
Beyond arithmetic, relational, logical, bitwise, and assignment types of operators, C includes a range of specialized ones that handle memory addresses, structure references, and more advanced tasks.
Let’s explore each special C operator in detail.
The conditional operator offers a compact way to handle simple decision-making in your programs. It evaluates a condition and selects one of two expressions based on whether the condition is true or false.
Unlike an if-else statement, which spans multiple lines, the conditional operator fits into a single expression, often making code more concise. It can streamline tasks such as choosing between two values, setting defaults, or performing quick validations.
Because it involves three operands — a condition and two results — it’s the only operator in C that requires three parts.
Here are the crucial details of conditional operator in C:
| Aspect | Details |
| Name of the Operator | Conditional operator aka Ternary operator |
| Symbol of the Operator | ?: |
| Syntax of the Operator | result = (condition) ? expression_if_true : expression_if_false; |
Example of Conditional Operator in C
Here’s a short program illustrating how it decides between two values based on a logical check:
#include <stdio.h>
int main() {
int score = 75;
const char* result = (score >= 40) ? "Pass" : "Fail";
printf("Exam Result: %s\n", result);
return 0;
}
Output:
Exam Result: Pass
Uses of the Conditional Operator
Use |
Description |
| Replacing Simple if-else | Quickly pick one of two values without writing multiple lines of conditional code |
| Setting Defaults | Assign a fallback value if a main condition isn’t met |
| Choosing Min/Max | Compare two numbers and select the smaller or larger one in a single expression |
| Inline Validations | Verify a condition on the fly before deciding what to store or display |
The sizeof operator in C tells you how much memory a data type or variable needs, measured in bytes. It’s evaluated during compilation, so it doesn’t slow down your program at runtime.
You might use sizeof to determine array lengths, allocate memory dynamically, or confirm that certain data types meet specific size requirements. Because C implementations can vary in how many bytes they assign to each type, sizeof is one of the most reliable ways to ensure consistent, portable code.
Here are the crucial details about sizeof operator in C:
Aspect |
Details |
| Name of the Operator | sizeof Operator |
| Symbol of the Operator | sizeof |
| Syntax of the Operator | sizeof(type or variable) |
| Return Value | Unsigned integer (type size_t) |
Example of sizeof Operator in C
Here’s a brief program that prints the sizes of common data types:
#include <stdio.h>
int main() {
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of double: %zu bytes\n", sizeof(double));
printf("Size of char: %zu byte\n", sizeof(char));
return 0;
}
Output:
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte
Uses of the sizeof Operator
Use |
Description |
| Portable Coding | Verifying data type sizes across different compilers or platforms |
| Array Length Calculations | Determining the number of elements by dividing total bytes by sizeof(elementType) |
| Low-Level System Programming | Checking structure alignment and padding for performance or hardware constraints |
The comma operator allows multiple expressions to be evaluated and executed in a single statement. Despite looking similar to the commas that separate function parameters, it works differently by evaluating each expression from left to right and returning the value of the last expression.
This operator in C can simplify code when you want to combine related tasks in one place, such as initializing multiple variables in a loop. Keep in mind that each expression is evaluated in sequence, but intermediate results are not stored unless explicitly assigned.
Here are the critical details about the comma operator in C programming:
Aspect |
Details |
| Name of the Operator | Comma Operator |
| Symbol of the Operator | , |
| Syntax of the Operator | (expression1, expression2, ..., expressionN) |
| Execution Order | Left to right, final value is that of the last expression |
Example of Comma Operator in C
Below is a program that uses the comma operator to initialize and update multiple variables in a single line:
#include <stdio.h>
int main() {
int a, b, c;
a = (b = 2, c = b + 3, c * 2);
// Here, b is set to 2, c becomes 5, and finally a is assigned c * 2 = 10
printf("a: %d\n", a);
printf("b: %d\n", b);
printf("c: %d\n", c);
return 0;
}
Output:
a: 10
b: 2
c: 5
Uses of the Comma Operator
Use |
Description |
| Combining Expressions in Loops | Efficiently update multiple variables in the loop control part, like in for (i=0, j=10; i<j; i++, j--) |
| Assigning Multiple Values in One Go | Evaluate and assign different values in a single statement |
| Chaining Calculations | Run smaller expressions sequentially, returning the last one’s result in assignments |
| Minimizing Lines of Code | Merge related operations together without extra statements |
The dot (.) and arrow (->) operators help you access members within structures and unions.
Both these types of operators make it easier to handle complex data types by cleanly referring to individual elements without cluttering your code with extra dereferencing steps. In many data structures — like linked lists or trees — these operators come into play frequently.
Here are some important details about these two types of operators:
Aspect |
Details |
| Name of the Operators | Dot Operator, Arrow Operator |
| Symbol of the Operators | . for direct structure access, -> for pointer-to-structure access |
| Syntax of the Operators | structureInstance.member or pointerToStructure->member |
Example of Dot and Arrow Operators in C
Below is a simple program showing how both operators are used with a structure and a pointer to that structure:
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p1 = {10, 20};
struct Point* ptr = &p1;
// Using the dot operator
printf("p1.x using dot: %d\n", p1.x);
printf("p1.y using dot: %d\n", p1.y);
// Using the arrow operator
printf("ptr->x using arrow: %d\n", ptr->x);
printf("ptr->y using arrow: %d\n", ptr->y);
return 0;
}
Output:
p1.x using dot: 10
p1.y using dot: 20
ptr->x using arrow: 10
ptr->y using arrow: 20
Uses of Dot (.) and Arrow (->) Operators in C
Use |
Description |
| Accessing Struct Members Directly | Retrieve or set fields using the dot operator on an actual structure |
| Accessing Struct Members via Pointer | Dereference pointers to structures with the arrow operator for cleaner code |
| Linked List Manipulation | Move through node pointers (current->next) and access node data |
| Object-Like Operations | Simulate object member access in C when working with more complex structs |
Pointers are a powerful feature in C, and the address-of (&) and dereference (*) operators lie at the heart of this mechanism.
By combining these two types of operators, you can work with memory directly, which is helpful for tasks like dynamic memory allocation, creating complex data structures, or passing large data efficiently. Although they might seem tricky at first, a solid grasp of & and * is key to writing flexible and optimized code in C.
Here are some key details you should know:
Aspect |
Details |
| Name of the Operators | Address-of Operator, Dereference Operator |
| Symbol of the Operators | & for address-of, * for dereference |
| Syntax of the Operators | pointer = &variable; value = *pointer; |
Example of Address-of (&) and Dereference (*) Operators in C
Below is a simple program to show how to take a variable’s address, store it in a pointer, and then use dereferencing to access the original data:
#include <stdio.h>
int main() {
int num = 42;
int *ptr = # // Address-of operator used to get num's address
printf("Address of num: %p\n", (void*)&num);
printf("Value of ptr (which is &num): %p\n", (void*)ptr);
printf("Value pointed to by ptr (*ptr): %d\n", *ptr);
// Modifying the value via pointer
*ptr = 100;
printf("Updated value of num after *ptr = 100: %d\n", num);
return 0;
}
Output:
Address of num: 0x7ffeea7ac9bc // Example address; will vary
Value of ptr (which is &num): 0x7ffeea7ac9bc
Value pointed to by ptr (*ptr): 42
Updated value of num after *ptr = 100: 100
Uses of Address-of (&) and Dereference (*) Operators
Use |
Description |
| Dynamic Memory Management | Using & with malloc or other allocation functions to manage data on the heap. |
| Passing Large Structures by Reference | Avoiding copying large data by passing pointers to functions instead of entire structures. |
| Building Linked Data Structures | Linking nodes in a linked list or tree by storing addresses in pointers. |
| Modifying Variables from Functions | Allowing functions to change the original variable using a pointer parameter. |
Operator precedence and associativity determine the order in which parts of an expression are evaluated. When multiple operators appear in the same statement, precedence dictates which operator runs first, and associativity decides how operators of the same level group together.
Being aware of these rules prevents unexpected results, especially in complex expressions. It also helps you write clearer code: well-placed parentheses can override default precedence, making your intent obvious to both the compiler and anyone reading your work.
Below is a streamlined overview that shows how operators stack up in priority.
Operator Group |
Examples |
Associativity |
| Highest Precedence | (), [], ->, . | Left to Right |
| Unary Operators | ++, --, !, ~, &, *, (type) | Right to Left |
| Multiplicative | *, /, % | Left to Right |
| Additive | +, - | Left to Right |
| Relational and Equality | <, >, <=, >=, ==, != | Left to Right |
| Logical AND / OR | &&, || | Left to Right |
| Conditional | ?: | Right to Left |
| Assignment | =, +=, -=, *=, /=, %=, etc. | Right to Left |
| Lowest Precedence | , (Comma operator) | Left to Right |
Example of Operator Precedence and Associativity in C
Here’s a program that demonstrates how precedence and associativity can affect an expression’s outcome. Changing parentheses can lead to different results if you’re not careful.
#include <stdio.h>
int main() {
int a = 2, b = 3, c = 4;
int result1 = a + b * c; // Multiplication first, then addition
int result2 = (a + b) * c; // Parentheses override default precedence
printf("Without parentheses: %d\n", result1);
printf("With parentheses : %d\n", result2);
return 0;
}
Output:
Without parentheses: 14
With parentheses : 20
Uses of Operator Precedence and Associativity
Use |
Description |
| Writing Complex Expressions | Preventing ambiguous operations by applying parentheses where needed |
| Avoiding Logic Errors | Ensuring that tricky combinations (like ++a + b++) behave as intended |
| Code Readability | Highlighting the intended evaluation sequence for others who read your code |
| Mathematical Calculations | Correctly handling multiple operations (e.g., mix of arithmetic, bitwise, and logical) |
| Simplifying Debugging | Reducing the chance of subtle errors by making operator order explicit |
Operators in C are often described by how many operands they work with.
Understanding these categories clarifies how different operators function and helps you choose the most appropriate one for a given task.
Here are some crucial details:
Number of Operands |
Examples |
| 1 (Unary) | ++a, --a, !a, ~a |
| 2 (Binary) | a + b, a - b, a & b, `a |
| 3 (Ternary) | (condition) ? expression1 : expression2 |
Example Demonstrating Unary, Binary, and Ternary Types of Operators
Below is a simple program that shows how these three categories of operators can appear in a single piece of code:
#include <stdio.h>
int main() {
int a = 5, b = 3;
// Unary: Increment 'a'
++a; // a becomes 6
// Binary: Add 'a' and 'b'
int sum = a + b; // 6 + 3 = 9
// Ternary: Check which is bigger
int bigger = (a > b) ? a : b; // evaluates to 6
printf("After unary increment, a: %d\n", a);
printf("Sum of a and b: %d\n", sum);
printf("Bigger number: %d\n", bigger);
return 0;
}
Output:
After unary increment, a: 6
Sum of a and b: 9
Bigger number: 6
Uses of Unary, Binary, and Ternary Operators
Operator Type |
Typical Scenarios |
| Unary | Incrementing loop counters, negating numbers, checking logical NOT |
| Binary | Arithmetic operations (+, -), bitwise manipulation (&, `) |
| Ternary | Quick branching in a single expression, choosing one of two values based on a condition |
Software Development Courses to upskill
Explore Software Development Courses for Career Progression
Even experienced developers can stumble when working with the various types of operators in C. Misunderstanding precedence or syntax can lead to bugs that are difficult to trace.
Below are the most frequent errors developers make when using operators in C language and how to avoid them.
Avoiding these mistakes ensures your code is both accurate and maintainable. This sets the stage for implementing best practices to write efficient C programs.
Writing clean and efficient code involves a combination of smart operator usage and optimization techniques. Following best practices simplifies debugging and enhances code performance.
Below are practical tips for working with types of operators in C and writing efficient code.
Also Read: How to Become a Software Engineer in India? 7 Actional Steps
If you aim to deepen your understanding of programming and advance your career, upGrad is here to guide you. With over 10 million learners worldwide, 200+ expertly designed courses, and partnerships with 1400+ hiring companies, upGrad equips you with the knowledge and skills needed to thrive in a competitive environment.
Below are some courses from upGrad that align with mastering all types of operators in C and programming fundamentals.
You also have access to personalized one-on-one expert career counseling. These sessions help you identify your goals, improve your resume, and craft a career strategy tailored to your skills.
Operators are special symbols that tell the compiler to perform specific mathematical, relational, or logical manipulations. They act as the connectors between variables and constants, allowing developers to construct complex logic. Without these tools, variables would remain static and unable to interact with one another.
C programming classifies these tools into six main categories: Arithmetic, Relational, Logical, Bitwise, Assignment, and Special/Miscellaneous operators. Each category is designed for a specific function, ranging from basic calculations to low-level memory manipulation, covering every aspect of system-level programming needs.
Precedence determines the order in which expressions are evaluated when multiple symbols appear in one line. For example, multiplication is performed before addition. Understanding this hierarchy is essential to avoid logic errors, as it dictates which part of a complex formula the compiler calculates first.
The Ternary operator (? :) is a unique tool that acts as a shorthand for if-else statements. It takes three operands: a condition, a result if true, and a result if false. It is widely used to write concise conditional logic in a single line of code.
The single equals sign (=) is an assignment tool used to store a value into a variable. In contrast, the double equals sign (==) is a relational tool used to compare two values. Confusing these two is a common source of bugs for beginners.
Bitwise tools allow developers to manipulate data at the bit level (0s and 1s). This is crucial for systems programming, embedded devices, and cryptography, where direct hardware control and memory efficiency are required. They offer a level of precision that higher-level abstraction tools cannot match.
When you divide two integers (e.g., 5 / 2), the system truncates the decimal part and returns an integer result (2). To get the exact decimal value, at least one of the numbers must be cast to a floating-point type before the calculation occurs.
Logical tools, such as AND (&&), OR (||), and NOT (!), are used to test multiple conditions simultaneously. They return either true (1) or false (0) and are fundamental for controlling program flow in decision-making structures like if statements and while loops.
The sizeof tool is a compile-time unary operator that returns the amount of memory (in bytes) allocated to a variable or data type. It is essential for writing portable code, as data type sizes can vary between different computer architectures and compilers.
Unary tools are those that require only a single operand to function. Common examples include the increment (++) and decrement (--) operators, as well as the logical NOT (!). They are frequently used in loops to update counters or flip boolean states efficiently.
The Modulus operator returns the remainder of a division operation between two integers. It is frequently used in algorithms to check for even or odd numbers, cycle through array indices, or restrict a number within a specific range, making it a versatile tool for logic building.
Associativity dictates the direction (left-to-right or right-to-left) in which operators of the same precedence level are processed. For instance, assignment flows right-to-left, while arithmetic usually flows left-to-right. Knowing this helps developers predict exactly how complex expressions with multiple similar symbols will resolve.
Compound assignments combine an arithmetic operation with a value assignment in one step. For example, x += 10 adds ten to x and saves the result. These shorthand symbols make code more concise, easier to read, and can sometimes help the compiler optimize performance.
A frequent error is assuming that chained comparisons like a < b < c work algebraically. In C, this evaluates (a < b) first, returning 1 or 0, and then compares that result to c. This often leads to incorrect logic unless separated by logical AND (&&) operators.
Yes, they use "short-circuit" evaluation. For an AND (&&) operation, if the first condition is false, the second is not checked. For an OR (||) operation, if the first is true, the second is ignored. This feature improves efficiency and prevents potential runtime errors.
Left Shift (<<) and Right Shift (>>) move the bits of a number to the left or right, effectively multiplying or dividing by powers of two. These are highly efficient tools used in performance-critical applications like graphics processing and data compression algorithms.
The address-of operator (&) retrieves the memory address of a variable, while the dereference operator (*) accesses the value stored at that address. These tools are the backbone of C's powerful memory management capabilities, allowing for dynamic allocation and complex data structures.
Without precedence rules, expressions would be ambiguous. For instance, in 3 + 4 * 5, precedence ensures multiplication happens first, yielding 23. If order didn't exist, it might yield 35. Mastering this hierarchy ensures your mathematical logic behaves consistently across different compilers and platforms.
No, standard C does not support overloading, which is the ability to define custom behaviors for symbols like + or - for user-defined types. This feature is available in C++, but in C, symbols have fixed, predefined meanings to keep the language simple and predictable.
The Dot (.) operator is used to access members of a structure variable, while the Arrow (->) operator is used when accessing members via a pointer to a structure. These tools are essential for organizing related data and managing complex records in C programs.
Reference Link:
https://www.statista.com/statistics/793628/worldwide-developer-survey-most-used-languages/
417 articles published
Rohan Vats is a Senior Engineering Manager with over a decade of experience in building scalable frontend architectures and leading high-performing engineering teams. Holding a B.Tech in Computer Scie...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources