Operators and Expression in C

In this post we are going to explain about various Operators available in C language, and expressions to use them.

Introduction

C language has a wide range of operators which are built in.
An Operator is a symbol that tells the computer to perform certain mathematical or logical manipulations
Operators are used in programs to manipulate data and variables.They usually form a part of the mathematical or logical expression.

C operators are classified into eight different categories:

  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
An expression is sequence of operands and operators that reduces to a single value.
         For e.g 12 -8
             is an expression whose value is 4. The value can be typed other than void.

Back to Top
Arithmetic operator


We have already used arithmetic operators in our previous posts. Arithmetic operators which C provides are listed below in the table:

Operator
Meaning
+
Addition Or Unary plus
-
Subtraction Or unary minus
*
Multiplication
/
Division
%
Modulo

The operators listed above work as usually as they are expressed in mathematics normally. They can operate on any built in data type allowed in C.

The integer division truncates any fractional part. The modulo division operation produces the remainder of an integer division.

Example of how can you use these operators:

   A+B
   A-B
   A*B
   A/B
   A%B (This operation has a draw back as they cannot be used on Floating point values)

Here in above examples A and B are operands and the sign between them are called operators(More specifically - Arithmetic Operators)

When both the operands are integers then that expression is said to be integer expression.The integer expression always gives out integers values only.
Lets take one example
   A=25   B=4 
(Here the largest value of an integer depends on the data type and the type of the machine as pointed in earlier posts also)
   A+B=29
   A-B=21
   A*B=100
   A/B=6 (decimal part truncated)
   A%B=1(remainder of division)

During modulo The sign of the division is always the sign of the first operand

  -25%-4 = -1
  -25%4  = -1
   25%-4 =  1

The arithmetic operation done only on the real values or real operands are called real arithmetic operation.
   D= 25.0/4.0 = 6.25

When one of the operand is integer and other is real then the operation is called mixed mode arithmetic.
   25/4.0 = 6.25
   Whereas, 25/4 =6

Back to Top
Relational Operators

We often compare two quantities and depending on their relation, take certain decisions. These comparison , in C language, can be done by relation operators.
Below shown are the Relational operators:
Operator
Meaning
< 
Is smaller than
> 
Is greater than
<=
Is smaller than or equal to
>=
Is greater than or equal to
==
Equality check
!=
Is not equal to

These operators are used to compare two values such as:

   A<B (A is smaller than B)
   A>B(A is greater than B)
   A<=B(A is smaller than or equal to B)
   A>=B(A is greater than or equal to B)
   A==B( A is equal to B)
   A!=B(A is not equal to B)

When arithmetic operators are used along side with relational operators such as:

   A+B >P+Q

Then first the arithmetic operation is encountered and solved and then the results between operands are being compared using relational operators.

That means that Arithmetic operator has a higher priority than relational operator.

Logical Operators

In addition to Relation Operators C also has Logical operators. 
They are :
   &&   logical AND
    ||       logical OR
    !       logical NOT

An expression combining two relational expressions is called logical expression.

   A>B && C<D
   A>=B  ||  C<D

Here the && operator denotes that both the relational operators should be true. If either of them or both of them will be false (i.e if A will be smaller than B Or C>D OR both of these) than the given logical expression will be false

The logical OR(||) expression denotes that if one of the relational expression is true than the logical expression is true else if both of them are false then the logical expression is false.

Back to Top
Assignment Operator

Assignment operators are used to assign the result of an expression to a variable. We have seen the usual assignment operator '='. 

But there are some other assignment operators known as 'Shorthand assignment Operators' which are quiet useful and easier to read and understand, also they are more concise and efficient.
They are:
+=
-=
*=
/=
%=

Statement with simple assignment operator
Statement with shorthand assignment operator
A=A+B
A +=B
A=A-C
A -=B
A=A*10
A *=10
A=A/10
A /=10
A=A%B
A %=B

As showed in the above table, these operation works on those variables on which, assignment includes their own presence on the right hand side.
If you will read each case n the above table you will easily get to understand how to represent a simple assignment expression in a shorthand assignment expression.

Back to Top
Increment and Decrement Operator

There are two very useful operators in C which allows you to increment the value of variable by 1 or decrement the value of variable by 1.

They are : ++ and --
We might have already used them in some of our previous examples in our previous posts.

They are extensively used in for and while loop.
Basically there are two subclass of theses operators they are:
Postfix increment decrement operator and Prefix increment decrement operator.

If there is a operand A then,

A++ (postfix increment)
++A(prefix increment)
A-- (postfix decrement)
--A (Prefix decrement)

They all results the same individually,but if included in an assignment expression then may vary the end result.
For e.g .
 then,
          {
           int A=5, M;
           M=A++;
           printf("M=%d A=%d",M,A);
           }
           Output : M=5 A=6
   
           {
             int A=5,M;
             M=++A;
             printf("M=%d A=%d",M,A);
           }
           Output: M=6 A=6

Here in the first example while assigning the value to M first the value of A is assigned to M then A is incremented, while in the second example the value of A is increment first and then it is assigned to M because it is a prefix increment operation, this sentence may confuse you so read the below sentence for second example.
M=++A;
that means, M= incremented value of A;

Note that same is the case with prefix or postfix decrement operation.

RULES to use them:

  • They can only be used with variables as they are unary operators.
  • When postfix (++ or --) is used in an expression than the expression is evaluated first using the original value and then the value of that operator is incremented or decremented accordingly.
  • When prefix (++ or --) is used in an expression than the expression is evaluated after the original value incremented or decremented accordingly.

Back to Top
Conditional operator

A conditional operator or we can say Ternary operator pair " ? : " is available in C to construct conditional expression of the form:
   exp1?exp2:exp3
Where exp1,exp2,exp3 are three different expression
for example,
   p=10 , q=12

   a=(p>q)?p:q ;
 
   The above conditional statement acts as,
                  if(p>q)
                             {
                                a=p;
                               }
                  else
                          {
                            a=q;
                           }

Back to Top
Bitwise Operator

C supports some special operators known as bitwise operators for manipulation of data at bit level.
These operators are used for testing bits, or shifting then right or left. Bitwise Operator may not apply to float or double.
Below table shows the list of Bitwise operators:

Operator
Meaning
&
Bitwise AND
|
Bitwise OR
^
Bitwise exclusive OR
<< 
Shift left
>> 
Shift right

Back to Top
Special Operator:

There are various operators that we have to use compulsorily as a part of syntax of some functions or statements, while some are used for the ease of calculations or use.
some of them are comma, sizeof operator, pointer operators(&, *), member selection operator such as( . , ->).

Comma operator
The coma operator is used to separate variable in expression while declaration or while they are called in the functions.
for e.g. , int a,b,c;
               printf("%d %d %d",a,b,c);
It is also used in while loops and for loops for the same reasons.

Sizeof operator
This operator is very useful for allocating memory according to the sizeof the data type of that particular variable.
   syntax: sizeof(variable); OR sizeof(datatype);
here this statement will return the default size of the data type of the variable.

Other two Special Operators will be discussed in future posts when they will be used.

Type conversion in Expressions

Implicit type conversion

C allows the use of different types of variable in an expression and converts them , so that they can be evaluated  without loosing their significance. This automatic conversion is known as implicit type conversion. While the evaluation of expression is going on, the type conversion is done following some strict rules.

  • In a expression the operands of lower data types are converted into higher data types before the operation precedes.
  • Hence because of the above rule, the result is in higher data type.
    • for e.g,
                                 int i,x;
                                 float f;
                                 double d;
                                 long int 1;
                                   x=1/i + i*f -d;
    • Here 'i' is changed to long in 1/i and to float in i*f because long int is higher than int, and float is also higher than int
    • In the second step the result of 1/i which will be in long int, than converted in to float and then the result of 1/i  + i*f  which will be in float will be converted into double.
    • Below image shows how the conversion takes place step by step.

    Type conversion example

Explicit type conversion

Many times we know that there is type conversion needed and we force the program to do so. This kind of conversion is called explicit type conversion.
Let me give you one example: Consider a ratio of number of females per males
Here the number of females and males wont be in a floating point value but the ration of them can come out to be a floating point value, hence, just by using the above formula will give a result with the integer part of the result only not the fractional part.

Hence we can write:  ratio = (float)number_of_females/Number_of_males
Here we have explicitly converted the int value of number of females in to floating point value hence when divided by the int value of Number of males will give out the integer as well as fractional part in the float result of the final ratio.

Operator Precedence and Associativity :

The precedence is used to determine how an expression involving more than one operator is evaluated. There are distinct levels of precedence and an operator may belong to one of these level. It is obvious with the fact that the operator with higher precedence will be evaluated first and the operator with lower precedence will be evaluated after the higher ones.
The operators on the same level may be evaluated from the right to left or left to right of an expression depending on the level on which the operator is. This property is called as associativity property.
Below table shows the precedence and associativity property of various operator.

Operator
Description
Associativity
Rank
( )
[ ]
Function call
Array element reference
Left to right
1
+
-
++
--
!
`
*
&
Sizeof
(type)
Unary Plus
Unary Minus
Increment
Decrement
Logical negation
Ones complement
Pointer reference
Address
Size of an object
Type cast(conversion)
Right to left
2
*
/
%
Multiplication
Division
Modulo
Left to right
3
+
-
Addition
Subtraction
Left to right
4
<< 
>> 
Left shift
Right shift
Left to right
5
< 
<=
> 
>=
Less than
Less than or equal to
Greater than
Greater than or equal to
Left to right
6
= =
|=
Equality
Inequality
Left to right
7
&
Bitwise AND
Left to right
8
^
Bitwise XOR
Left to right
9
|
Bitwise OR
Left to right
10
&&
Logical AND
Left to right
11
||
Logical OR
Left to right
12
?:
Conditional expression
Left to right
13
=
*= /= %=
+= -+ &=
^= |=
<<= >>=
Assignment operator
Right to left
14
,
Comma operator
Left to right
15

Comments

Popular posts from this blog

Windows phone Wifi connectivity problem.

Create Excel file using Java: Apache POI - PART - 2: Line Chart