Introduction

  • Operators are the term used to describe the action to be taken between two data operands.
  • Operators allow us to perform different kinds of operations on operands.
  • An operand is a sub-expression/value on which an operator acts.

Definition 

  • An Operator is a symbol/special character that tells the compiler to perform certain mathematical or logical manipulations.It performs a specific operation (evaluation) on one or more operands in a given expression and give a specific results.

Features

  • Operators are used in programs to manipulate data and variables.
  • Operators are the backbone of any program.
  • They are used for everything from very simple functions like counting to complex algorithms like security encryption.
  • C operators join individual constants and variables to form expressions.
  • Expressions are made by combining operators between operands.

Types of Operators

  • There are several classifications of operators and each of them can have one or more operands, a specific data that is to be manipulated. Broadly, there are following types of operators used in C –
(A) Arithmetic Operator
    • The operators which are used in mathematical calculations/operations are called arithmetic operators.
    • An operator that performs an arithmetic (numeric) operation such as +, -, *, /, or % is called arithmetic operator.
    • Arithmetic expressions in C are written in straight-line form. Thus ‘a divided by b’ is written as a/b.
    • Types of Arithmetic Operator :
      • All the arithmetic operators are categorized into – (a) Binary operator and (b) Unary operator.  When an arithmetic operation requires single operand, this operator is called Unary operator.

(a) Binary Arithmetic Operator :

      • When an arithmetic operation requires two operands, these operators are called Binary operators.
      • When an operator uses two operands in their mathematical calculations in an expression to work it properly is known as Binary operator.
      • There are following binary arithmetic operators used in C:
Slno. Operator Symbols Operator Name Example
01.
+
Addition
a+b 
8+5=13
02.
Subtraction
a-b 
8-5= 03
03.
*
Multiplication
a*b
8*5= 40
04.
/
Division/Integer Division
a/b
8/5=1
05.
%
Modulo/Remainder Division
a%b
8%5= 03

      • When a binary arithmetic operator works between –
        • an integer and integer always yields an integer result.
        • a float and float yields a float result.
        • a integer and float yields a float result.
        • a integer and double yields a double result.
      • An important example of division and Modular division operators are as follows –
         Division Operation                      Result
                       3/5                                      0
                       5/3                                      1
                       5.0/3                                  1.3
                       5/3.0                                  1.3
                       5.0/3.0                               1.3
         Modular Division Operation    Result 
                       3%5                                     3
                       5%3                                     2
(b)Unary Arithmetic Operator :
      • The operator required single operand in their calculations in an expression to work it properly.
      • C contains two types of unary operators –

(i) Increment (++) operators :

        • The increment operator increments the variable value by one in one go.
        • This operator can be written in two forms i.e. before a variable or after a variable i.e. on this basis, increment operator is further divided into two parts –
          • Pre – Increment Operator( such as ++i)
            • If an increment operator is written before a variable, it is referred to as pre-increment operators. It is represented as ++i and is equivalent to i = i+1.
            • The prefix increment operator follows “change then use” rule.
          • Post – Increment Operator( such as i++)
            • If an increment operator is written after a variable, it is referred to as post increment operator. It is represented as i++ and is equivalent to i = i+1.
            • The postfix operator follows “use then change” rule.
        • The importance of pre and post operator occurs while they are used in the expressions.

(ii) Decrement (- -) operators :

          • The decrement operator decreases the variable value by one in one go.
          • This operator can be written in two forms i.e. before a variable or after a variable. On this basis, decrement operator is further divided into two parts –
            • Pre – Decrement Operator(such as –i)
              • If an decrement operator is written before a variable, it is referred to as pre-decrement operators. It is represented as –i and is equivalent to i = i -1.
              • The prefix decrement operator follows “change then use” rule.
            • Post – Decrement Operator(such as i–)
              • If an decrement operator is written after a variable, it is referred to as pre-decrement operators. It is representd as i– and is equivalent to i = i -1.
              • The postfix decrement operator follows “use then change” rule.
          • The importance of pre and post operator occurs while they are used in the expressions.      
(B)Relational/Comparison Operator
    • Those operators which are used to determine/test the relationship between two values in an expression are called relational operator.
    • Relational operators usually appear in statements which are inquiring about the truth of some particular relationship between variables.
    • These operators in C are normally appear between the parentheses symbol.
    • All relational operators are binary operators and therefore require two operands.
    • A relational expression returns zero when the relation is false and a non-zero when it is true.
    • The relational operators are –        
Slno.
Operator Symbols
Operator  Name
Expression
/Example
Meaning
 01.  ==  Equal to  x==y   x is equal to y 
 02.   !=  Not equal to    x!=y   x is not equal to y 
  03.   <   Smaller/Less than  x<y    x is less than y 
 04. <=  Less than or equal to   x<=y    x is less than or equal to y 
 05.  > Greater than   x>y   x is greater than y 
 06. >= Greater than or equal to  x>=y   x is greater or equal to y 

                                                     

(C)Logical Operator
    • Logical operators are used to evaluate expressions which may be either true or false.
    • The logical operators are : –
      Operator                                        Name/Meaning
           &&                                                  Logical AND
             ||                                                    Logical OR
              !                                                    Logical NOT
    • The logical operators (AND and OR) combine two conditions and logical NOT works with single condition and is used to negate the condition i.e. if the condition is true, Logical NOT negates it to false and vice versa.
    • The (!) operator perform the Boolean operation NOT. It has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand.
    • The truth table of logical operators are –  
X Y X && Y
 0/False   0/False   0/False  
 0/False   Non zero/True 0/False  
Non zero/True   0/False  0/False 
Non zero/True  Non zero/True  1/True 
                
X Y X || Y
 0/False   0/False   0/False  
 0/False   Non zero/True 1/True 
Non zero/True   0/False  1/True 
Non zero/True  Non zero/True  1/True 
                 
X !X
 0/False  1/True
 1/True 0/False

  • The logical operators && and || are used when evaluating two expressions to obtain a single relational result.
  • The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true and false otherwise.
    • The operator || corresponds with Boolean logical operation OR.This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. To understand the use || OR operator, let us take the possible results of a || b.
  • For Example:
    • !(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true.
    • !(6 <= 4) // evaluates to true because (6 <= 4) would be false.
    • !true // evaluates to false
    • !false // evaluates to true.
    • ((5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
    • ((5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
(D) Assignment Operator
    • Denoted by equal (=) symbol.
    • It is used to assign value to the variables.
    • For example  int A = 12; int A = B; int C= A+B; char ch=’m’; float x=3.14; etc.
    • Multiple assignments are also possible in the following format: –
Syntax : –  Identifier A= Identifier B= Identifier C=. . . = Expression
In this case, all the identifiers are assigned the same value of expression.
Example : – A=B=520+x+y+z; (this is the same if you write: A=786+x+y+z; and B=786+x+y+z;)
    • Assignment operator can be represented in the form of shorthand form in an expression, therefore, they can also be represented as – 
Slno. Shorthand Operators Name  Use Equivalent Form
01. += Addition shorthand assignment operator  A += B   A = A + B
02. -= Subtraction shorthand assignment operator  A -= B  A = A – B
03. *= Multiplication shorthand assignment operator   A *= B  A = A * B
04. /= Division shorthand assignment operator  A /= B  A = A / B
05. %= Remainder Division shorthand assignment operator  A %= B  A = A% B
06. &= And shorthand assignment operator  A &= B  A = A & B 
07. |= OR shorthand assignment operator  A |= B  A = A | B 
08. ^=  Exponent shorthand assignment operator  A ^= B  A = A ^ B  
09. <<=  Left Shift shorthand assignment operator  A <<= B  A = A << B  
10. >>=  Right Shift shorthand assignment operator A >>= B  A = A >> B  
11. >>>=    A >>>= B  A = A >>> B  
Shorthand Operator
      • The shorthand works for all unary operators in C.
      • It is also popularly called as compound assignment.
      • It is a special case of assignment operator representation in shorthand form.
      • The shorthand operators are mainly used to increment and decrement a variable by 1 or certain values.
      • Shorthand assignment operator combines one of the arithmetic or bitwise operators with assignment operator.
      • Shorthand operator is implemented mostly to assign an expression to a variable in a shorter way hence some times it is also called Shorthand Assignment Operator.
(E) Conditional/Ternary Operator(? 🙂
  • C has a unique operator called the conditional operator (?:) which is closely related to the if-else structure.
  • This operator is found only in C language.
  • It takes/works on three operands hence the name ternary. The operands together with the conditional operator form a conditional expression. The first operand represents condition, the second operand represents the value of the entire conditional expression if the condition is true and the third operand is the value for the entire conditional expression if the condition is false.
  • The syntax is :
                      (condition)? (expression1): (expression2);
    If condition is true, expression1 is evaluated else expression2 is evaluated. Here Expression1 or Expression2 may also be further a conditional expression as in the case of nested if statement.
  • Examples –
    • x= (y<41) ? 23: 5;
      if (y<41)condition is true, then x=23 else x=5;
    • printf (“%s\n”, grade>=40 ? “Passed” : “failed”);
      If condition will true then print “passed”  else it will print “failed”.
    • (x>y) ? printf (“x is greater than y \n”) : printf (“y is greater than x \n”);
(F) Bitwise Operator
  • Each Bitwise operator allows to manipulate integer variables at each bit level.
  • Bitwise operators are used to modify the bits of the binary pattern of the variables.
Operators Name Representation Description
>> Right shift/ Shift Right

A >> B

Shift bits of A right by distance B, 0 is introduced to the vacated most significant bits, and the vacated least significant bits are lost. The following shows the number 43-shifted right once (43 >> 1).
0101011 = 43
0010101 = 21
<< Left Shift/Shift Left A << B Shift bits of A left by distance B , the most significant bits are lost as the number moves left, and the vacated least significant bits are 0. The following shows the number 43 shifted left once (43 << 1).
>>> Right shift unsigned A >>> B Shift A to the right by B bits. Low order bits are lost. Zeros fill in left bits regardless of sign example.
~ Bitwise Not/ complement ~B The bitwise Complemnt changes the bits. 1, into 0, and bit 0, to 1.
The following shows the complement of number 43.
0101011 = 43
1010100 = 84
& Bitwise AND A & B AND is 1 if both the bits are 1 otherwise AND is 0. The bitwise AND is true only if both bits are set.
Consider 23 & 12:
10111 = 23
01100 = 12
00100 = 4
| Bitwise OR A | B The bitwise OR is true if either bits are set. Or if the bit is 1 if either of the two bits is 1, otherwise it is 0.
Consider 23 | 12:
10111 = 23
01100 = 12
11111 = 31
^ Bitwise Exclusive OR A ^ B The bitwise Exclusive OR is true if either bits are set, but not both. XOR of the bits is 1 if one bit is 1 & other bit is 0, otherwise, it is 0.
Consider 23 ^ 12:
10111 = 23
01100 = 12
11011 = 27
(G) Boolean Operator
    • Boolean operators allow us to combine the results of multiple expressions to return a
      single value that evaluates to either true or false.
Operators Name  Representation Description
&& Conditional AND   A && B
If both A and B are true, result is true.
If either A or B are false, the result is false. But if A is false, B will not be evaluated.
For example, (A > 20 && B <= 50) will evaluate to true if A is greater than 20, and B is less than or equal to 50.
|| Conditional OR A || B
If either A or B are true, the result is true. But if A is true, B will not be evaluated.
For example, (A > 10 || B > 10) will evaluate to true if either A or B are greater than 10.
! Boolean NOT ! A
If A is true, the result is false. If A is false, the result is true.
& Boolean AND  A & B 
If both A and B are true, the result is true. If either A or B are false, the result is false and both A and B are evaluated before the test.
Boolean OR A | B 
If either A or B are true, the result is true. Both A & B are evaluated before the test.
^ Boolean XOR A ^ B
If A is true and B is false, the result is true. If A is false and B is true, the result is true. Otherwise, the result is false. Both A and B are evaluated before the test.
(H) Special Operators
Comma Operator
      • A comma operator is used to separate a pair of expressions.
      • A pair of expressions separated by a comma is evaluated left to right.
      • The type and value of the result are the value of the type and value of the right operand.
      • The comma operator gives left to right evaluation of expressions.
      • It enables to put more than one expression separated by comma on a single line.
      • While declaration multiple variables and providing multiple arguments in a function, comma works as a separator.Example: int a,b,c; In this statement, comma is a separator and tells to the compiler that these (a, b, and c) are three different variables.
      • The left side of comma operator is always evaluated to void.
      • The comma operator is represented by the token comma (,)
      • It is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type).In another words, It is a binary operator that evaluates its first operand, performs all side effects and discards the result, and then evaluates the second operand and returns its value and type so: x = (y, z);
      • The comma operator has the lowest order of precedence of any C operator, and acts as a sequence point.
      • Generally, comma operator (,) is used in the for loop.
      • Example: – int i = 20, j = 25; here, comma is used as a separator between the two statements.
Type Casting/Type Conversion Operator
      • Type casting/conversion is the process of changing an variable of one data type into another as per need of the program.
      • In another words, Converting an expression of a given type into another type is known as type casting.
      • In a Programming language such as C/C++, smaller memory data type variable can be converted to large data type by the compiler. It is required to make the language robust. When a variable of int type is multiplied by a variable of float type then the output is saved inside the computer system memory as double data type. Thus C/C++ permits mixed expressions.
      • Type Conversion is made automatically by compiler whereas, Type Casting is also to be explicitly done by the programmer.
      • Normally constants and variables of different types are mixed in an expression, they are converted to the same type using type conversion process.
      • Type conversion can be done by following two ways: – (i)Automatic/Implicit Type Conversion  (II) Explicit Type Conversion.

(i) Automatic/Implicit/Indirect Type Conversion –

        • When type conversion is done by the compiler automatically, without any external trigger from the user, it is called Automatic/Implicit Type Conversion.
        • When an expression consists of more than one type of data elements in an expression, the C/C++ compiler converts the smaller data type element in larger data type element. This process is known as implicit or automatic conversion.
        • It takes place normally when an expression contains more than one data type.
        • The following rules are imposed in automatic type conversion – 
-> All chars and short ints are converted to ints.
-> All floats are converted to doubles.
-> In case of binary operators –
      if one of the two operands is a long double, the other operand is                     converted to long double,
      else if one operand is double, the other is converted to double,
      else if one operand is long, the other is converted to long,
      else if one operand is unsigned, the other is converted to unsigned. Thus, C converts all operands ‘up’ to the type of largest operand.

(ii) Explicit/Direct Type Conversion –

        • When type conversion is done by the programmer manually, as per need of the program, it is called Explicit Type Conversion.
        • In this conversion, the programmer convert one data type into another data type by writing certain syntax.
        • The following rules are imposed in explicit type conversion –
          1. To convert into explicit type It is possible to force an expression to be of specific type we use an operator called a cast which can be used by using following syntax as given : –
                   (type) expression    [where type is the standard C data type.]
          2. cast is an unary operator and has the same precedence as any other unary operator.
          3. For example –  
int c=50;
float x;
x=(float)c/3;
Sizeof() Operator
      • The sizeof operator is the most common operator in C.
      • It is a compile-time unary operator that is used to compute the size of any object is called sizeof() operator.
      • In other words, the sizeof operator determines the amount of memory required(memory size) for an object/datatype at compile time rather than at run time.
      • The sizeof operator can be used to find how many bytes are required for an object to store in memory.
      • It returns the size of a variable. It can be applied to any data type, float type, pointer type variables etc.
      • Syntax  – sizeof object or  sizeof(datatype name);
      • It results an unsigned integer value equal to the size of the specified object or type in bytes.
      • sizeof() , while looking like a function call, is actually an operator and part of the language core. No inclusion is needed as any specific header files. It requires size_t file which is defined in various header file such as stddef.h , string.h , stdlib.h , and stdio.h . Including any one of these are enough to use size_t in our code.
      • It returns the size (memory occupied) of a given object/variable/data type in bytes as unsigned integer.An object can be a variable or array or structure.
      • It gives the exact total bytes needed in memory to represent the type or value or expression.
      • It can be applied to any data type such as int, float, double, char, pointer, class, structure, union type of variables/data types etc.
      • For example – The size of an int is really compiler dependent. Back in the day, when processors were 16 bit, an int was 2 bytes. Nowadays, it’s most often 4 bytes on a 32-bit and 8 bytes on a 64-bit systems. Still, using sizeof(datatype/variablename/int/float) is the best way to get the sizeof an integer data type for the specific system the program is executed on.
      • For example –
sizeof(char) = 1bytes
sizeof(int) = 2 bytes
sizeof (float)= 4 bytes
if k is integer variable, then sizeof (k) = 2 bytes
Pointer Operator : 
      • To manipulate data using pointers, the C language provides two operators : – (i) Indirection Operator (ii) Address Operator
Indirection/dereference Operator(*)
      • The indirection operator is a unary operator represented by the symbol (*).
      • While a pointer pointing to a variable provides an indirect access to the value of the variable stored in its memory address, the indirection operator de-references the pointer and returns the value of the variable at that memory location.
      • Here, dereferencing means taking away the reference and giving the value what it was actually referring to i.e. Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer.
      • Dereferencing a null pointer is undefined behavior in C,
      • It operates on a pointer variable, and returns an l-value equivalent to the value at the pointer address.
Address of Operator/Reference Operator (&)
      • Address operator is denoted by a symbol ‘&'(ampersand).
      • It is a unary operator i.e. it requires one operand.
      • This operator returns the address of the variable associated with the operator.
      • It is pointer address operator and when used as a prefix with a variable,it gives the address of the variable.
      • for example &n, this gives the address of variable n to a pointer.
    Member Selection Operator(. / ->)
        • Dot (.) and Arrow (->) symbols are used as Member Selection Operators.
        • It is also some times called  Dot(.) and Arrow(->) Operator.
        • The dot member selection operator ( . ) is preceded by an object’s name or with a reference to an object to access the object’s members.
        • The dot (.) operator is used for direct member selection via object name.
        • The arrow member selection operator (->) is preceded by a pointer to an object to access the object’s members.
        • In C, to access the members of a structure & union individually, the dot operator is used. On the other hand, to access members of a structure/union individually through a pointer, the arrow operator is used.

    Priority/Precedence Order & Associativity of Operators

    • When more than one operators are used together in an expression to solve a particular problem then to determine which operators execute first, a rule is implemented to do so . For this, C/C++/Java uses a certain hierarchy and priority order to solve such kind of mixed expressions. The hierarchy and associativity of the operators are explained in the given table.
    • In the table, the operators written in the same line have the same priority. The higher precedence operators are written first.
    • Expressions are evaluated based on operator precedence and associativity rules when an expression contains more than one operator.
    •  The rule of priority of operators is called Operator Precedence.It dictates the order of evaluation of operators in an expression.
    • Associativity 
      • It defines the order in which operators of the same precedence are evaluated in an expression i.e. from left to right or right to left.
      • It is sometimes called Grouping.
      • It defines the precedence order in which operators are evaluated in the case that there are several operators of the same level in an expression.
      • When we write a complicated expressions and are not completely sure of the precedence levels, then we can always include parentheses for that expression.
      • It also makes our code easier to read.
    Priority/Order of Precedence Operator Lists Associativity
    Highest  ( )
    Left to right
      ! ++ — (type) sizeof Right to left
      / % Left to right
      + – Left to right
      < <= > >= Left to right 
    Optimum  == != Left to right
      && Left to right
      || Left to right 
      ?: Right to left
      = += -= *= /= %= &&= ||= Right to left  
    Lowest  , Left to right
             

    Loading

    Categories: C

    0 Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.