View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Unary Operator in C

Updated on 28/02/20255,679 Views

The unary operator in C is used to perform operations on a single operand. It allows you to manipulate variables by applying operations like incrementing, decrementing, and logical negation.

Common unary operators include the increment (++), decrement (--), and negation (!) operators. The unary operator is essential for simplifying expressions and making code more efficient.

In this tutorial, you will learn how to use the unary operator in C programs to perform various operations on single variables.

Improve your C programming skills with our Software Development courses — take the next step in your learning journey!

Overview of the Unary Operator in C

The unary operator in C is used to perform operations on a single operand. It is primarily used to modify or check the value of variables in a simple and concise way.

Unary operators are essential for various common operations such as incrementing, decrementing, negating values, and inverting bits.

They are classified into different types:

Operator

Description

Use Case

Increment (++)

Increases the value of a variable by 1.

Often used in loops to increment counters.

Decrement (--)

Decreases the value of a variable by 1.

Common in loops to decrement counters or to track back.

Logical NOT (!)

Inverts the boolean value (0 becomes 1, non-zero becomes 0).

Used for condition checking to negate conditions or boolean expressions.

Bitwise NOT (~)

Inverts all bits of the operand.

Used in bit manipulation tasks where all bits are flipped.

Unary Minus (-)

Negates the value of the operand (turns positive to negative and vice versa).

Used for negating values in arithmetic operations.

Unary Plus (+)

Has no effect, but clarifies the operand is positive.

Used to indicate a positive number (often redundant, but can improve readability).

Unary operators are used across a variety of scenarios, such as:

  • Arithmetic operations like incrementing or decrementing counters in loops.
  • Logical operations for negating conditions in decision-making (e.g., if statements).
  • Bitwise operations for manipulating bits in tasks like encryption or data compression.
  • Simplifying expressions by changing the sign of numbers or explicitly marking values as positive.

Unary operators are versatile and are often used to simplify code, making it more compact and efficient, especially when performing basic operations on single variables.

Also Read: Types of Operators in C: Roles, Usage & Best Practices 2025

Now that you have a basic understanding of what unary operators are, let’s dive deeper into the different types of unary operators in C and explore how each one works in various scenarios.

Types of Unary Operators in C

Unary operators in C are used to perform operations on a single operand. Each type of unary operator has its own specific functionality and use cases in programming. Let's explore the different types of unary operators in C in more detail with examples, explanations, and real-world use cases.

1. Unary Plus (+) Operator

The unary plus operator does not change the value of the operand but can improve code readability by explicitly indicating that a value is positive.

int x = +5;
printf("%d\n", x);  

Output:

5

Explanation: The unary plus does not modify the value of x, it simply indicates that the value is positive, which is especially useful when dealing with negative values or in mathematical expressions.

Use Case: The unary plus operator is often used for clarity, though it doesn’t alter the value. It can be useful when you want to emphasize a positive value, especially in complex expressions or calculations.

2. Unary Minus (-) Operator

The unary minus operator negates the value of the operand. If applied to a positive value, it makes the value negative, and vice versa.

int x = 5;
printf("%d\n", -x);  

Output:

-5

Explanation: The unary minus takes the value of x (which is 5) and makes it negative, producing -5.

Use Case: This operator is commonly used to negate values in calculations, such as in algorithms that involve changes in direction or sign, like vector computations or financial calculations (e.g., converting positive amounts to negative debts).

3. Increment (++) Operator

The increment operator increases the value of its operand by 1. It can be used in two ways: pre-increment and post-increment.

int x = 5;
x++; // Post-increment: x is used first, then incremented.
printf("%d\n", x);

Output:

6


int y = 5;
++y; // Pre-increment: y is incremented first, then used.
printf("%d\n", y);

Output:

6

Explanation:

  • Post-increment (x++) increases the value of x after its current value is used in the expression.
  • Pre-increment (++x) increases the value of x before it is used.

Use Case: The increment operator is widely used in loops to iterate through values, especially in for and while loops. It’s also common when manipulating counters or tracking occurrences in algorithms (e.g., counting iterations or events).

4. Decrement (--) Operator

The decrement operator decreases the value of its operand by 1. It can be used similarly to the increment operator with pre-decrement and post-decrement versions.

int x = 5;
x--; // Post-decrement: x is used first, then decremented.
printf("%d\n", x);

Output:

4


int y = 5;
--y; // Pre-decrement: y is decremented first, then used.
printf("%d\n", y);

Output:

4

Explanation:

  • Post-decrement (x--) uses the value of x first, then decreases it.
  • Pre-decrement (--x) decreases the value of x before it is used.

Use Case: The decrement operator is used in loops (especially when counting down or reversing a sequence). It's also useful for algorithms that need to reduce values, such as when processing items in reverse order or tracking back through an array.

5. Address of (&) Operator

This operator returns the memory address of its operand. It’s used to work with pointers in C.

int x = 5;
printf("%p\n", &x);

Output:

Memory address of x

Explanation: The & operator gives you the memory address where the variable x is stored, which is useful when working with pointers.

Use Case: The address-of operator is critical when using pointers to access or modify values in memory. It's essential for dynamic memory allocation, passing large structures or arrays to functions, and working with arrays and linked lists.

6. sizeof() Operator

The sizeof operator returns the size (in bytes) of its operand. It’s a compile-time operator that helps determine the memory usage of data types.

int x;
printf("%zu\n", sizeof(x));  

Output:

4 (on most systems, size of an int)

Explanation: The sizeof operator evaluates the size of the variable or data type at compile-time and returns the result in bytes.

Use Case: The sizeof operator is frequently used in memory management, such as allocating memory dynamically or determining the size of data types and structures. It's also used in array bounds checking.

7. Dereferencing (*) Operator

The dereference operator is used to access the value at the memory address pointed to by a pointer.

int x = 10;
int *p = &x;
printf("%d\n", *p);

Output:

10

Explanation: The dereference operator (*p) gives the value stored at the memory address p points to.

Use Case: The dereference operator is used in pointer manipulation, such as accessing or modifying values stored in dynamically allocated memory or working with data structures like linked lists.

8. Logical NOT (!) Operator

The logical NOT operator inverts the logical state of its operand. If the operand is true (non-zero), it returns false (0); if the operand is false (0), it returns true (1).

int x = 0;
printf("%d\n", !x);

Output:

1 (because x is 0, !x becomes 1)

Explanation: The ! operator is used to negate the logical value of its operand, flipping true to false and vice versa.

Use Case: The logical NOT operator is widely used in decision-making and conditions, particularly in if statements to invert boolean values. It's also helpful in validating conditions or creating logical checks in algorithms.

9. Bitwise NOT (~) Operator

The bitwise NOT operator inverts each bit of its operand, flipping 1s to 0s and 0s to 1s.

int x = 5;  // Binary: 00000101
printf("%d\n", ~x);

Output:

-6 (Binary: 11111010)

Explanation: The ~ operator flips all the bits of the operand. In two’s complement representation, the result is the negative of the operand with all bits inverted.

Use Case: Bitwise NOT is used in tasks involving low-level operations, such as manipulating flags, working with hardware, and performing bitwise data operations like compression or encryption.

Understanding and using these operators effectively can lead to cleaner, more readable, and optimized code.

Also Read: String Function in C with Examples

With a clear grasp of the different unary operators, it’s time to see how they are used in real-world applications. Let’s look at some examples where these operators help simplify code and improve performance.

Real-World Applications of Unary Operators in C

Unary operators in C are versatile and widely used in various real-world programming scenarios. They simplify operations on single variables, especially in algorithms that involve counters, memory manipulation, or boolean logic.

Below are a few key areas where unary operators play an important role:

1. Looping and Iteration

The increment (++) and decrement (--) unary operators are most commonly used in loops for iterating over arrays, counting iterations, or updating counters. These operators are essential for efficient loop execution.

Example: Counting with a For Loop

int i;
for(i = 0; i < 10; i++) {
printf("%d\n", i);
}

Output:

0, 1, 2, ..., 9

Use Case: Used in for, while, or do-while loops for incrementing or decrementing loop counters, making the code cleaner and more concise.

2. Pointer Manipulation and Memory Management

The address-of (&) and dereferencing (*) operators are extensively used in dynamic memory allocation, pointer manipulation, and managing data structures like linked lists, trees, or arrays.

Example: Accessing Memory Location

int x = 10;
int *p = &x;
printf("Value at address: %d\n", *p);

Output:

10

Use Case: Used for pointer arithmetic, accessing and modifying data directly in memory, and managing complex data structures like linked lists and trees.

3. Negating Values in Algorithms

The unary minus (-) operator is frequently used in algorithms that require value negation, such as balancing equations, reversing signs, or implementing specific mathematical functions like finding the opposite direction in vector calculations.

Example: Reversing the Sign

int a = 5;
int b = -a; // b will be -5
printf("%d\n", b);

Output:

-5

Use Case: Often used in financial applications to represent debt or profit, physics simulations for reversing vector directions, or algorithmic problem-solving that involves negative results.

4. Memory Size Calculation

The sizeof unary operator is extremely useful in situations that require dynamic memory allocation or for determining how much memory a variable or data structure occupies.

Example: Finding the Size of a Data Type

int x;
printf("Size of int: %zu\n", sizeof(x));

Output:

4 (on most systems)

Use Case: Widely used in dynamic memory allocation, file handling systems, and performance optimization techniques to calculate memory requirements for storing data.

5. Logical and Bitwise Operations

The logical NOT (!) and bitwise NOT (~) operators are used for condition checking and low-level bitwise operations, such as flag manipulation, encryption, or system-level programming.

Example: Checking for Non-zero Condition

int x = 0;
if(!x) {
printf("x is zero\n");
}

Output:

x is zero

Use Case: Logical NOT is commonly used for conditional statements and negating boolean values. Bitwise NOT is used in networking applications, cryptography, and other low-level operations like data compression.

6. Memory Address Access

The address-of (&) operator is key for interacting with low-level memory and hardware interfaces. It’s commonly used in embedded systems programming and system-level applications.

Example: Passing Address to a Function

void increment(int *num) {
(*num)++;
}

int main() {
int value = 5;
increment(&value);
printf("%d\n", value);
}

Output:

6

Use Case: Essential for passing arguments by reference to functions, modifying data directly without returning values, and working with hardware registers in embedded systems.

7. Optimization in Mathematical Calculations

The increment (++) and decrement (--) operators are particularly helpful in optimizing mathematical computations by directly manipulating variables in complex equations or loops.

Example: Optimized Calculation in a Loop

int sum = 0;
for(int i = 1; i <= 10; ++i) {
sum += i;
}
printf("%d\n", sum);

Output:

55

Use Case: Used to optimize mathematical formulas where incrementing or decrementing values is required, such as calculating sums, averages, or aggregating results.

8. Flag Manipulation

The bitwise NOT (~) operator is used to manipulate flags in settings where binary representation is critical, such as turning specific bits on or off.

Example: Toggling a Flag Bit

unsigned int flags = 0b1010;  // Binary: 1010
flags = ~flags; // Binary: 0101
printf("%u\n", flags);

Output:

5

Use Case: Common in network protocols, hardware communication, or file permissions, where toggling specific flags can enable or disable certain features.

From basic tasks like incrementing counters to complex tasks like memory management, bitwise operations, and flag manipulation, unary operators help developers write efficient, readable, and optimized code.

They are crucial in areas like systems programming, embedded systems, algorithm optimization, and low-level memory access.

Also Read: Top 25+ C Programming Projects for Beginners and Professionals

While unary operators are useful in many situations, it’s important to follow best practices to avoid common mistakes. Let’s explore some tips that will help you use unary operators effectively and write cleaner code.

Best Practices and Tips for Using the Unary Operator in C

The unary operator in C provides efficient ways to perform operations on a single operand. To use it effectively and avoid common mistakes, it’s important to follow best practices that enhance clarity, maintainability, and efficiency in your code.

Below are some key tips and best practices for using unary operators.

Tip/Best Practice

Explanation

Mind operator precedence

Always use parentheses when necessary to ensure the correct order of operations when combining unary operators with other operators.

Keep it simple and readable

Use unary operators for straightforward operations like incrementing or negating values. Avoid overusing them in complex expressions.

Limit nesting and complexity

Avoid excessive nesting of unary operators, as it can make the code hard to read. For complex logic, consider using more explicit statements.

Use increment/decrement carefully

Be mindful when using ++ and -- operators in expressions to avoid side effects, especially with post-increment and post-decrement.

Beware of side effects

Unary operators like ++, --, and & can modify variables. If an expression has side effects, it’s often clearer to break it into individual statements.

Avoid common mistakes

Watch for common mistakes like incorrect use of the address-of (&) operator or dereferencing a null pointer, which can lead to undefined behavior.

This table provides best practices for using the unary operator in C, helping you avoid common pitfalls and write clean, maintainable code.

Also Read: Command Line Arguments in C Explained

By following the best practices, you can maximize the benefits of unary operators, but it’s also important to consider their limitations. Let’s take a closer look at the advantages and potential drawbacks of using unary operators in your code.

Benefits and Drawbacks of Using the Unary Operator in C

Unary operators in C provide a compact and efficient way to perform operations on single operands. However, when misused or overused, they can introduce complexities that make the code harder to understand.

Below is a breakdown of the benefits and drawbacks of using unary operators:

Aspect

Benefits

Drawbacks

Conciseness

Unary operators make code more concise by allowing operations to be performed in a single line.

Overuse in complex expressions can make the code difficult to read and understand.

Readability for Simple Operations

Improves readability for simple operations, such as incrementing or negating values, making the code cleaner.

For complex expressions, unary operators can reduce clarity, especially if nested.

Efficient Code

Unary operators simplify code by reducing the need for additional statements, making operations more efficient.

Can result in side effects (e.g., modifying variables unintentionally) when used improperly.

Memory Access & Pointer Manipulation

The address-of (&) and dereferencing (*) operators simplify pointer manipulation and memory access.

If misused (e.g., dereferencing null pointers), unary operators can lead to undefined behavior and crashes.

Performance

Unary operators like ++ and -- optimize performance for simple tasks like iteration or counters.

Excessive use of post-increment or post-decrement in expressions can introduce bugs due to side effects.

Operator Precedence

Unary operators have clear precedence, and their behavior is predictable when used alone.

If combined with other operators without proper parentheses, it can cause unexpected results due to operator precedence.

The unary operator in C is powerful for simple tasks but should be used with caution when the logic becomes complex. While it makes the code efficient and compact, excessive use or poor structuring can lead to readability issues and potential bugs.

Also Read: Top 9 Popular String Functions in C with Examples Every Programmer Should Know in 2025

You now have a solid understanding of the unary operator’s pros and cons. Test your knowledge with this quiz to see how well you grasp the concepts and their applications.

Quiz to Test Your Knowledge on the Unary Operator in C

Assess your understanding of the unary operator in C, including its syntax, usage, and real-world applications. Answer the following multiple-choice questions:

1. Which of the following unary operators is used to decrease the value of a variable by 1?

a) ++

b) --

c) -

d) +

2. What does the unary minus (-) operator do in C?

a) Increments the value of its operand

b) Negates the value of its operand

c) Returns the memory address of its operand

d) Inverts the bits of its operand

3. Which of the following is the correct syntax for using the dereference operator in C?

a) &x

b) *x

c) x*

d) &*x

4. What will the following code print?

int x = 10;
printf("%d\n", -x);

a) 10

b) -10

c) 0

d) Error

5. Which unary operator is used to obtain the address of a variable in C?

a) *

b) ++

c) --

d) &

6. What does the sizeof operator do in C?

a) Returns the size of the data type in bytes

b) Returns the value of a variable

c) Returns the address of a variable

d) Increments the value of a variable

7. What will the following code output?

int a = 5;
int *p = &a;
printf("%d\n", *p);

a) 5

b) Address of a

c) 0

d) Error

8. Which of the following is a valid use of the increment (++) operator in C?

a) x = ++y;

b) ++x = y;

c) ++(x + y);

d) x++ = y;

9. What happens when you apply the unary bitwise NOT (~) operator on the value 5 (in binary: 00000101) in C?

a) It returns 5

b) It returns -6

c) It returns 1

d) It returns 0

10. Which of the following scenarios is not suitable for using the unary operator in C?

a) Incrementing a variable in a loop

b) Accessing memory address using pointers

c) Modifying the sign of a variable

d) Performing complex multi-step conditions

This quiz will test your understanding of unary operators, their syntax, and how they are used in C to simplify tasks such as memory access, incrementing/decrementing values, and more.

Also Read: 25 Most Common C Interview Questions & Answers [For Freshers]

Well done on completing the quiz! To continue expanding your skills in C programming and stay ahead of the curve, consider upskilling with upGrad’s expert-led courses to learn more about advanced programming concepts and real-world applications.

upGrad’s courses provide expert training in C programming, covering key concepts such as the unary operator, decision-making techniques, and efficient coding practices. You’ll gain hands-on experience by solving real-world programming challenges, including implementing the unary operator for practical scenarios like checking eligibility or assigning values.

Below are some relevant upGrad courses to elevate your programming skills and advance your career:

You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!

Similar Reads:

Explore C Tutorials: From Beginner Concepts to Advanced Techniques

Addition of Two Numbers in C: A Comprehensive Guide to C Programming

String Anagram Program in C

C Program to check Armstrong Number

Array in C: Introduction, Declaration, Initialisation and More

Exploring Array of Pointers in C: A Beginner's Guide

What is C Function Call Stack: A Complete Tutorial

Discovering C Operators: An Overview with Types and Examples!

Binary Search in C

C Enum Type: Definition and Practical Implementation

Factorial Program of a Number in C

15 Most Important Features of C Language

Fibonacci Series Program in C Using Recursion

Basics of File Handling in C

How to Use the For Loop in C Effectively?

Format Specifiers in C Programming

FAQs

1. What is the difference between pre-increment (++x) and post-increment (x++) in C?

Pre-increment increases the value of the variable before it is used in an expression, while post-increment increases the value after the variable's current value is used.

2. Can unary operators be applied to constants in C?

Yes, unary operators can be applied to constants. For example, -5 will negate the value of 5, and +5 simply indicates the positive value of 5.

3. How does the unary minus (-) operator work with data types in C?

The unary minus operator negates the value of the operand. It works with both signed and unsigned types, but applying it to unsigned types can result in unexpected behavior, especially if the value exceeds the range of the type.

4. What happens if you use the unary address-of (&) operator on a constant or literal in C?

You cannot use the unary address-of operator (&) on constants or literals because they do not have memory addresses. Using &5 would cause a compile-time error.

5. What is the result of applying the logical NOT (!) operator to a non-zero value?

The logical NOT operator inverts the truth value of the operand. If the operand is non-zero (true), it becomes 0 (false), and if the operand is 0 (false), it becomes 1 (true).

6. Can unary operators be chained together in C?

Yes, unary operators can be chained, but care should be taken to avoid confusing expressions. For example, ++i++ is invalid, but i++ and ++i can be used separately in expressions.

7. How does the unary operator sizeof() handle arrays in C?

The sizeof() operator returns the size of the data type or expression in bytes. When applied to an array, sizeof() returns the total memory used by the array (i.e., sizeof(array) = number of elements * size of element).

8. Is it possible to apply the unary dereference (*) operator on an uninitialized pointer in C?

Dereferencing an uninitialized or NULL pointer results in undefined behavior. It’s important to ensure that a pointer is initialized before dereferencing it.

9. How does the bitwise NOT (~) operator work in two's complement representation in C?

The bitwise NOT operator inverts every bit of its operand. In two’s complement representation, this inverts the bits and adds 1 to the result, effectively computing the negative equivalent of the operand minus one.

10. What are the side effects of using the increment/decrement operators (++, --) in C expressions?

The increment and decrement operators can cause side effects, especially when used within larger expressions. For example, using x++ in an expression causes the current value of x to be used first, then it increments, potentially causing logical errors.

11. Can you use the unary operator sizeof() with dynamically allocated memory in C?

Yes, sizeof() can be used with dynamically allocated memory, but it only returns the size of the pointer itself, not the memory allocated. To find the size of dynamically allocated memory, you need to track the size manually or use specialized memory management functions.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.