What is the difference between Unary and Binary Operators in C and C++?

Difference between Unary and Binary Operators in C, C++

Difference b/w Unary and Binary Operators - In this section you will learn about Unary and Binary Operators. What are they and why they used and how to use these operators in our C and C++ programs?

What is an Operator?

Operator is a symbol or special character which is used to perform a specific task, the task/meaning of operator is defined in the compiler. For example + is a operator which is used to add two values.

What are Unary Operators?

The Operators which operate on Single Operand known as Unary Operators, some of the unary operators are:

    ++		Increment Operator
    --		Decrement Operator
    &		Address Of Operator
    -		Unary Minus Operators
    ~		(One's Compliment) Negation Operator
    !		Logical NOT
and so on..
Let's understand by example:
#include <stdio.h>
 
int main()
{
    int x=10;
    int y;
     
    y=(-10);
     
    printf("x=%d, y=%d\n",x,y);
    printf("Address of x: %08X\n",&x);
 
    return 0;
}

Output

x=10, y=-10
Address of x: 8C668378

In the given example we are using two operations based on Unary operator:

(-10) here - is a Unary Minus operator which is operating an action with 10 and value of y will be -10.

&x here & is a Unary Address of Operator which is returning the address of variable x.

What are Binary Operators?

The Operators which operate on Two Operands known as Binary Operators, some of the binary operators are:

    +	Binary Plus Operator
    -	Binary Minus Operator
    ==	Equal to Operator
    <	Less than Operator
    and so on..
Let's understand by example:
#include <stdio.h>
 
int main()
{
    int x,y;
    int res1,res2;
     
    x=10;
    y=20;
     
    res1=x+y;
    res2=(x==y);
     
    printf("res1: %d, res2: %d\n",res1,res2);
 
    return 0;
}

Output

res1: 30, res2: 0

In the given example we are using two operations based on Binary operator:

x+y here + is a Binary Plus Operator which is adding values of x and y and return 30 in res1 variable.

x==y here == is a Binary Equal to Operator which is comparing values of x and y and return 0 in res2 variable because values of x and y are not same.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.