Operators and Expressions
Operators and Expressions
EXPRESSIONS
Introduction
• Operator is a symbol that tells the computer to perform
certain actions on variables (or) expressions. An expression is
a sequence of operands and operators that reduces to a
single value.
• C operators can be classified into a number of categories.
They include:
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
2
Arithmetic Operators
Example: Integer Arithmetic
• If a = 14 and b = 4 we have the following results:
• During integer division, if both the operands are of the same sign, the result is
truncated towards zero.
• If one of them is negative, the direction of truncation is implementation
dependent. That is, 6/7 = 0 and -6/-7 = 0
• but -6/7 may be zero or -1. (Machine dependent)
• Similarly, during modulo division, the sign of the result is always the sign of the
first operand (the dividend). That is
4
Example: Real Arithmetic
• A real operand may assume values either in
decimal or exponential notation.
• Since floating point values are rounded to the
number of significant digits permissible, the final
value is an approximation of the correct result.
• If x, y, and z are floats, then we will have:
x = 6.0/7.0 = 0.857143
y = 1.0/3.0 = 0.333333
z = -2.0/3.0 = -0.666667
• The operator % cannot be used with real operands.
5
Example: Mixed-mode Arithmetic
• When one of the operands is real and the other is
integer, the expression is called a mixed mode
arithmetic expression.
• If either operand is of the real type, then only the real
operation is performed and the result is always a real
number.
• Example:
6
Relational Operators (1)
• We often compare two quantities and depending on their
relation, take certain decisions.
• For example, we may compare the age of two persons, or
the price of two items, and so on.
• These comparisons can be done with the help of relational
operators.
• An expression such as a < b or I < 20 containing a relational
operator is termed as a relational expression.
• The value of a relational expression is either one or zero. It is
one if the specified relation is true and zero if the relation
is false.
• For example 10 < 20 is true but 20 < 10 is false.
7
Relational Operators (2)
8
Example: Relational Operators
When arithmetic expressions are used on either side of
a relational operator, the arithmetic expressions will be
evaluated first and then the results compared. That is,
arithmetic operators have a higher priority over
relational operators.
Suppose i=1, j=2 and k=3
9
Logical Operators
The logical operators
&& and ||are used
when we want to
test more than one
condition and make
decisions.
13
Assignment Operators
• Assignment operators are used to assign the result of
an expression to a variable.
• We have seen the usual assignment operator, “=‟.
• In addition, C has a set of shorthand assignment
operators. Example:
14
Advantages of using short-hand
Assignment Operators
• What appears on the left-hand side need not
be repeated and therefore it becomes easier
to write.
• The statement is more concise and easier to
read.
• The statement is more efficient.
15
Increment and Decrement Operators (1)
• C allows two very useful operators not
generally found in other languages.
• These are the increment and decrement
operators: ++ and - -
• The operator ++ adds 1 to the operand, while --
subtracts 1.
• However, the operator ++ and - - can be used
either as pre increment or post increment form.
16
Increment and Decrement Operators (2)
• A pre increment operator first adds 1 to the
operand and then the result is assigned to the
variable on left.
• On the other hand, a post increment operator
first assigns the value to the variable on left
and then increments the operand.
17
Example: Increment and Decrement Operators
19
Conditional Operators
• Conditional/ternary operator is one which
contains three operands.
• The only ternary operator available in C
language is conditional operator pair “?:”.
• It has the following syntax:
exp1?exp2:exp3;
• This operator works as follows:
exp1 is evaluated first. If the result is true then
exp2 is executed otherwise exp3 is executed.
20
Example: Conditional Operators
• a = 10; b = 15;
x = (a > b ? a : b);
In this expression the value of b (15) will be
assigned to x.
21
Bitwise Operators (1)
• C has a distinction of supporting special
operators known as bitwise operators for
manipulation of data at bit level.
• These operators are used for testing the bits,
or shifting them right or left.
• Bitwise operators may not be applied to float
or double.
22
Special Operators
24
Comma Operator (,)
• The comma operator can be used to link the related
expressions together.
• A comma-linked list of expressions are evaluated left to
right and the value of right-most expression is the
value of the combined expression.
• For example, the statement
value = (x = 10, Y = 5, x+y); first assigns the
value 10 to x, then assigns 5 to y, and finally assigns
15 (i.e. 10 + 5) to value.
• Since comma operator has the lowest precedence of
all operators, the parentheses are necessary.
• Some applications of comma operator are: for loops
and while loops
25
Sizeof Operator
• The sizeof is a compile time operator and, when used with
an operand, it returns the number of bytes the operand
occupies.
• The operand may be a variable, a constant or a data type
qualifier.
• Examples:
m = sizeof(sum);
n = sizeof (long int);
27
Evaluation of Expressions
• Expressions are evaluated using an assignment statement of
the form: variable = expression
• variable is any valid C variable name.
• When the statement is encountered, the expression is
evaluated first and the result then replaces the previous
value of the variable on the left hand side.
• All variables used in the expression must be assigned values
before evaluation is attempted. Examples of evaluation
statements are
29
Operator Precedence table
30
Example: Hierarchy of Operations
31
Type Conversions in Expressions
• Implicit Type Conversion
– C permits mixing of constants and variables of different
types in an expression.
– C automatically converts any intermediate values to
the proper type so that the expression can be
evaluated without loosing any significance.
– This automatic conversion is known as implicit type
conversion.
– During evaluation it adheres to very strict rules of type
conversion.
– If the operands are of different types, the 'lower' type
is automatically converted to the 'higher' type before
the operation proceeds.
– The result is of the higher type.
32
Process of Implicit Type Conversion
33
34
35
Implicit Type Conversion
• The final result of an expression is converted to the
type of the variable on the left of the assignment sign
before assigning the value to it.
• However, the following changes are introduced during
the final assignment.
1. float to int causes truncation of fractional part.
2. double to float causes rounding of digits.
3 long int to int causes dropping of the excess
. higher order bits.
36
Explicit Conversion
Thereareinstanceswhenwewant to force atype conversion inaway
thatisdifferentfromtheautomaticconversion.
Consider,forexample,thecalculationofratiooffemalestomalesina
town. float ratio, int female_number,male_number
•
ratio = female_number/male_number
•
Since female_number and male_number are declared as integers
intheprogram,thedecimalpartoftheresultofthedivisionwouldbe
•
lostand ratio would representawrongfigure.
37
Thisproblemcanbesolvedbyconvertinglocallyoneofthe variables
tothefloatingpoint asshown below:
ratio = (float)female_number/male _number
The operator(float) convertsthefemale_numbertofloatingpointfor
the purposeofevaluationoftheexpression.Thenusingtheruleof
automatic conversion,thedivisionisperformedinfloatingpoint
mode,thus retaining thefractionalpartofresult.
Notethatinnowaydoestheoperator(float)affectthevalueofthe
variablefemale_number.Andalso,thetypeoffemale_number
remains asint intheotherpartsoftheprogram.
37
Example: Use of Casts
putchar(c) - Sendacharactertothestandardoutputdevice.
rand()-Returnarandompositiveinteger.
sqrt(d)- Returnthesquarerootofd.
scanf( ...)-Enterdataitemsfromthestandardinputdevice
(argumentsarecomplicated–willseeinlaterchapters.)
tolower(c) - Convertlettertolowercase.
toupper(c) - Convertlettertouppercase.
39