operators

Operators & Expressions

Operator

  • An operator is a symbol or string that tells the computer to perform mathematical or logical manipulation

  • Operator can manipulate the data or variable in a program

  • Examples: +,&,*,^,%, etc

Expression

  • An expression consist of variables and constants separated by operators
  • Examples: C=A+B, X=Y && (Z || P), etc

Types of operators in C:

  1. Arithmetic Operators

  2. Relational Operators

  3. Logical Operators

  4. Assignment Operators

  5. Increment and decrement Operators

  6. Conditional Operators

  7. Bitwise Operators

  8. Special Operators

Note: Operators can be classified into three type on the basis of number of operands used

  • Unary operators (One operand is used)
  • Binary Operators (Two operands are used)
  • Ternary operators (Three operands are used)

1.Arithmetic Operator

  • Arithmetic Operators used to perform arithmetic operations

  • Following are the basic arithmetic operations present in C(Assume A=10, B=20)

    Operator

    Description

    Example

    +

    Adds two operands

    A + B will give 30

    Subtracts second operand from the first

    A – B will give -10

    *

    Multiplies both operands

    A * B will give 200

    /

    Divides numerator by de-numerator

    B / A will give 2

    %

    Modulus Operator and remainder of after an integer division

    B % A will give 0

Note: Modulus operator(%) is not applicable to float type of data

Unary Arithmetic Operators:

  • This operators operates on single operands

Ex. Unary Plus +

Unary Minus –

  • when unary minus(-) operator is applied on a operand it multiply -1 with that operand

  • ex. Assume X=8, -X converts the value of X to -8

Binary Arithmetic Operators:

  • This operator operates of two operands

Ex. a+b, a*b, a-b etc

Integer Arithmetic:

  • When all the operands in a single arithmetic expression are integer, expression is known as integer expression and operation is known as integer arithmetic.

  • It produce an integer value always as a result

    • Ex. assume a=6, b=5

    • a-b=1, a+b=11, a*b=30, a/b=1(fractional part is truncated),a%b=1

  • During integer division if both operands are of same sign, the result will be +ve. If one of them is -ve, the result is -ve (generally)

    • Ex. 10/5=2, -10/-5=2, -10/5=-2, 10/-5=-2

  • During modulo division the sign of the result is always the sign of the first operand

    • Ex. 10%4=2, -10%4=-2, 10%-4=2 (generally -ve sign is not used in modulus division)

Real Arithmetic:

  • An operation involving only real operands is called real arithmetic
  • A real operand value cab be either decimal or exponential notation

    • Ex. A=12.0/14.0=0.857143

    • B=3.0/9.0=0.333333

    • C=-4.0/6.0=0.666667

Mixed-mode Arithmetic:

  • When one of the operand is real and the other operand is integer then the expression is known as mixed mode arithmetic expression

  • If one operand is real type, then the result is real number

    • Ex. 3/2.0=1.5, 3/2=1

2.Relational Operator:

  • Relational operators are used to compare the values of operand or expression to produce a logical value

  • A logical value is either true or false

  • An expression that contains relational operator(s) is known as relational expression

  • The value of relational operator is true(1), or false(0)

  • C support six relational operators described as follows taking the assumption as A=10, B=20

Operator

Description

Example

==

Checks if the values of two operands are equal or not, if yes then condition becomes true.

(A == B) is not true.

!=

Checks if the values of two operands are equal or not, if values are not equal then condition becomes true

(A != B) is true.

>

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

<

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

Example:

Expression Value

7 < 10         TRUE(1)

10 <= 5+6  TRUE(1)

4.5 < -10    FALSE(0)

Assume x=10,y=5

x < y        FALSE(0)

x!=y         TRUE(1)

  • Among the relational operators some are complement of others as follows

    • > is complement of <=

    • < is complement of >=

    • == is complement of !=

  • So one of the above operator can be written as the complement of others as follows

    • !(x < y) is same as x >= y

    • !(x > y) is same as x <= y

    • !(x !=y) is same as x == y

3.Logical Operators:

  • These operators are used to perform logical operations on the given two variables.

  • There are 3 logical operators in C language.(Assume A=1, B=0)

Operator

Description

Example

&&

Called Logical AND operator. If both the operands are non-zero, then condition becomes true.

(A && B) is false.

||

Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true

(A || B) is true.

!

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.(Unary operator)

!(A && B) is true.

Logical Operator Truth Table :

Operator

Operand1

Operand2

Final Output

AND

True

True

True

True

False

False

False

True

False

False

False

False

OR

True

True

True

True

False

True

False

True

True

False

False

False

NOT

True

False

False

True

Example:

(8>9) && (23<25 )——–> False

(5>3) || (3<2) ———> True

!(5>21) ———————>True

4.Assignment Operator:

  • Assignment operators are used to assign the a value or an expression value to a variable

  • It is expressed as L-Value = R-Value

  • R-value can be variable, constant, expression, function name, array name etc

  • L-value can be only variable

  • Assignment can be simple assignment or it can be short hand assignment or compound assignment

Operators

Example

 Explanation 

Simple assignment operator

=

sum = 10

10 is assigned to variable sum

Compound assignment operators

+=

sum += 10

This is same as sum = sum + 10

-=

sum -= 10

This is same as sum = sum – 10

*=

sum *= 10

This is same as sum = sum * 10

/+

sum /= 10

This is same as sum = sum / 10

%=

sum %= 10

This is same as sum = sum % 10

&=

sum&=10

This is same as sum = sum & 10

^=

sum ^= 10

This is same as sum = sum ^ 10

 

The advantages of using shorthand are:

  • No repetition of left-hand side and thus the readability is good
  • The statement is more concise.
  • The statement is more efficient

Example for Demonstration:

x += 5 means

  • Find the place identified by x
  • Add 5 to it

But x = x + 5 means:

  • Evaluate x+5
    • Find the place identified by x
    • Copy x into an accumulator
    • Add 5 to the accumulator
  • Store the result in x
    • Find the place identified by x
    • Copy the accumulator to it

5.Increment Decrement Operators

C allows very useful operators that aren’t found generally in other languages. These are the increment(++) and decrement(–) operators.

The increment operator adds 1 to the operand, while decrement operator subtracts 1 and both these are unary operators.

These types are further divided into two sub divisions based on their functionality and they are:

  • Postfix
  • Prefix

In Postfix the value is first assigned to the variable on the left and it then increments(or decrements) the operand.

Example:

The ‘y’ will hold 2 and the postfix first assigns the value and then increments it by one.

In Prefix, the value is incremented and then assigned.

Example:

The ‘y’ will hold 3 now.

Increment and decrement operators are unary operators and they require variables as their operands. The precedence and associativity of ++ and – – operators are the same as that of unary + and unary –

 

6.Conditional Operator:

Ternary operator is a conditional operator available in C to construct conditional expressions of the form exp1? exp2:exp3

Here exp1, exp2,exp3 are the expressions.

The operator?: works as follows :

Exp1 is evaluated first. If true then exp2 is evaluated and becomes the value of the expression.If exp1 is false exp3 is evaluated and it is the value of the expression. Note that only one of the expressions after ‘?’ will be executed.

For Example:

Ternary operator works just like the If else statement.

Example Program

7.Bitwise Operators:

  • C also provides the facility of changing information at bit levels.
  • These operators are used to perform bit operations. Decimal values are converted into binary values which are the sequence of bits and bit wise operators work on these bits.
  • Bitwise operators cannot be applied to float and double i.e. decimal values.

Some of the operators are:

  • ~ bitwise Negation or Complement
  • & bitwise AND
  • |  bitwise OR
  • ^ bitwise exclusive OR
  • <<  shift left
  • >>shift right

Truth Table for Bitwise Operators:

x y x | y x & y x ^ y
0 0 0 0 0
0 1 1 0 1
1 0 1 0 1
1 1 1 1 0

Bitwise OR ( | )

Bitwise OR operator | takes 2 bit patterns, and perform OR operations on each pair of corresponding bits. The following example will explain it.

The Bitwise OR, will take pair of bits from each position, and if any one of the bit is 1, the result on that position will be 1. Bitwise OR is used to Turn-On bits as we will see in later sections.

Bitwise AND ( & )

Bitwise AND operator &, takes 2 bit patterns, and perform AND operations with it.

The Bitwise AND will take pair of bits from each position, and if only both the bit is 1, the result on that position will be 1. Bitwise AND is used to Turn-Off bits.

Bitwise XOR ( ^ )

Bitwise XOR ^, takes 2 bit patterns and perform XOR operation with it.

The Bitwise XOR will take pair of bits from each position, and if both the bits are different, the result on that position will be 1. If both bits are same, then the result on that position is 0.

Left shift Operator ( << )

The left shift operator will shift the bits towards left for the given number of times.

Let’s take the binary representation of 2 assuming int is 1 byte for simplicity.

Now shifting the bits towards left for 1 time, will give the following result

Now the result in decimal is 4. You can also note that, 0 is added as padding the in the position 0.

If you left shift like 2<<2, then it will give the result as 8. Therefore left shifting 1 time, is equal to multiplying the value by 2.

Right shift Operator ( >> )

The right shift operator will shift the bits towards right for the given number of times.

Let’s take the binary representation of 8 assuming int is 1 byte for simplicity.

Now shifting the bits towards right for 1 time, will give the following result

Now the result in decimal is 4. Right shifting 1 time, is equivalent to dividing the value by 2.

One’s Complement operator ( ~ )

One’s complement operator (Bitwise NOT) is used to convert each “1-bit to 0-bit” and “0-bit to 1-bit”, in the given binary pattern. It is a unary operator i.e. it takes only one operand.

 

Program for demonstration

8.Special Operators

The C language supports special operators like comma and sizeof operators.

Comma Operator

Comma operator is used in linking all related expressions in a way where the comma links the list of the expressions evaluated from left to right and the rightmost expression shows the combined expression’s value.

Example:

In for Loop, for (n=1,m=10,n<=m; n++,m++).

In this example, it first assigns the value 11 to x and then assigns 10 to z and later assigns 21 to variable val. Parentheses are necessary since Comma has the least precedence as compared to all the other operators.

 

 

The sizeof operator:

The sizeof operator is compile time operator and it gives the size of the operands in the bytes it occupies. The operand can be a variable or a constant or a data type.

Example:

The size of operator helps to determine structure size when the programmer does not know the size. It also helps in dynamic memory allocation.

Program for demonstration:

Precedence and Associativity

 Precedence of operators: Precedence rule decides order in which different operations are applied in an expression.
  • If more than one operators are involved in an expression then, C language has predefined rule of priority of operators.
  • The highest priority operator is applied first
  • For example 5 + 6 * 7 is calculated as 5 + (6 * 7) and not as (5 + 6) * 7

Associativity of Operators: The associativity rule  indicates in what order operators of equal precedence in an expression are applied.

  • If more than one operators are there with same precedence level then associativity rule is applied.
  • It may be Left-to-Right or Right-to-Left associativity
  • For example ‘*’ and ‘/’ have same precedence and their associativity is Left-to-Right, so the expression “50 / 5 * 6″ is treated as “(50 / 5) * 6″.

In an expression there may be more than one type of operators. In that situation both precedence rule and associativity rule is applied to evaluate the expression. Following table shows the precedence rule and associativity rule.

c-prec_assoc

 

  •  Comma operator is having lowest priority among all so it should be used carefully. The following program gives the output as 5
  • Example for demonstration of precedence of operators
Output : 0

Explanation: P(+) > P (Relational) > P(logical) > P(=)

  • Example for demonstration of Left to Right associativity

badbetween

  • Example for demonstration of Right to Left associativity
 Output: 7

Explanation:

It is executed from right to left
c>a…true…so..7
then, a>b?a:7 (we get from execution of the right ternary operator)
so o/p 7

Typecasting (Type Conversion)

  •  Type casting is a way to convert a variable from one data type to another data type
  • For example, if you want to store a floating point value into a integer then you can type cast float to int.
  • You can convert values from one type to another explicitly using the cast operator as follows:

  Syntax: (type_name) Expression

Type-Casting-in-CSharp

 Implicit Type Casting:type-casting

  • If one expression contains data of different types, then the compiler converts the lower level data(narrow type) to higher level data(widen type) automatically, which is called as Implicit type casting.
  • Example:  x=5/5.6; // The result of x will be in floating point form

Example:

int x=157;

double y=x;        //here the the value of x is automatically converted to double.

 

 

 

 

 

 

Explicit Type Casting:

  • Explicit type conversion is a type conversion which is explicitly defined within a program
  • Explicit casting requires a casting operator. Syntax: (Type_name) Expression
  • Here the data type with parenthesis is known as cast operator
  • The type_name is one of the standard C data types and the expression may be constant, variable or expression

Example:

x= (int)7.5 —>7

a=(int)24.9/(int)8.5 —->24/8

double y=124.23; x=(int)y;

 Output: 7