Operators in C | Part2

05 min read

 

4) Bitwise Operator: In C, the following 6 operators are bitwise operators.

  • & (bitwise AND):  It takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
  • | (bitwise OR): It takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.
  • ^ (bitwise XOR): It takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
  • << (left shift): It takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
  • >> (right shift): It takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.
  • ~ (bitwise NOT): It takes one number and inverts all bits of it

Following is example C program.

include<stdio.h>
int main()
{
    unsigned char a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
    printf("a = %d, b = %d\n", a, b);
    printf("a&b = %d\n", a&b); // The result is 00000001
    printf("a|b = %d\n", a|b);  // The result is 00001101
    printf("a^b = %d\n", a^b); // The result is 00001100
    printf("~a = %d\n", a = ~a);   // The result is 11111010
    printf("b<<1 = %d\n", b<<1);  // The result is 00010010
    printf("b>>1 = %d\n", b>>1);  // The result is 00000100
    return 0;
}

Output:

a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 250
b1 = 4



5) Conditional Operators: Conditional operators return one value if the condition is true and returns another value is condition is false. This operator is also called as ternary operator. In the below example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if-else conditional statements.

Syntax     :        (Condition? true_value: false_value);

Example :         (A > 100  ?  0  :  1);

 
 
6) Assignment Operators: In C, values for the variables are assigned using assignment operators. For example, if the value “10” is to be assigned to the variable “sum”, it can be assigned as “sum = 10;” There are two categories of assignment operators in C language. They are,

1. Simple assignment operator ( Example: = )
2. Compound assignment operators ( Example: +=, -=, *=, /=, %=, &=, ^= )

 

7) Special operators: Here are some of the special operators that the C programming language permits. 

  • '&' - This operator is used to get the address of the variable.
  • '*' - This is used as a pointer to a variable.
  • sizeof() - This is used to find the size of a varaible.
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error