Sei sulla pagina 1di 37

Types, Operators &

Expressions

CSE 105
Structured Programming Language (C)
Presentation - 3

CSE, BUET CSE-105 Structured Programming


Basic Data Types (K R 2.2) n

char
a single byte, holds one character in local character set
int
natural size of integers in the host machine
float
Single-precision floating point
double
double-precision floating point

2
CSE, BUET CSE-105 Structured Programming
Data type : char (K R 2.2) n

Qualifier Basic Size Range


of sign type (bits)

A single ASCII character


signed char 8 128 to 127 (27 to +27 1)
unsigned 0 to 255 (0 to +28 1)

unsigned 8-bits magnitude

signed 7-bits magnitude

1-bit sign: 1 means negative and 0 means positive


3
CSE, BUET CSE-105 Structured Programming
Data type: int (K R 2.2) n

Qualifier Qualifier Basic type Size (bits) Range


of sign of size
int 16 or 32 host m/c dependent

signed short int 16 32768 to 32767


(215 to +215 1)
unsigned short int 16 0 to 65535
(0 to +216 1)
singed long int 32 2,147,483,648 to 2,147,483,647
(231 to +231 1)
unsigned long int 32 0 to 4,294,967,295
(0 to +232 1)

4
CSE, BUET CSE-105 Structured Programming
Data types: floating points (K R 2.2) n

float
single-precision
double
double-precision
long double
extended-precision

All of these types are implementation dependent


They can be of one, two or three distinct sizes.

5
CSE, BUET CSE-105 Structured Programming
Caution with floating point (K R 2.2) n

Consider following code:

value of x will be very close to zero e.g. 10-7. Hence this wont
work correct code is:

6
CSE, BUET CSE-105 Structured Programming
Constants : Numeric (K R 2.3) n

data type Example of constant octal hex

int 1234 02322 0x4d2

long int 123456789L 0726746425L 0x75BCD15L

unsigned long int 123456789UL 0726746425UL 0x75BCD15UL

double 123.45 or 123.45e-3 N/A N/A

float 123.45F or 123.45e-3F N/A N/A

long double 123.45L or 123.45-3L N/A N/A

7
CSE, BUET CSE-105 Structured Programming
Constants : Character (K R 2.3) n

A character constant is an integer, which can be presented in


different formats:
`A` : represents ASCII 65th character i.e., A
int var = `A` + 10; // value of var will be 75

`0` : represents ASCII 48th character i.e., zero


int var = `0` + 10; // value of var will be 58

`\0101` : represent octal 101. `A` = 6510 = 1018


`\x41` : represent hexadecimal 41. `A` = 6510 = 4116
Character constants can participate in numeric operations just as
any other integer.

8
CSE, BUET CSE-105 Structured Programming
Constant : Escape Sequence (K R 2.3) n

Back slash \ is called escape character


Characters following \ bear special meaning as follows:

\a bell character = `\007` \0 null termination for string


\b backspace \\ back slash
\f formfeed \? question mark
\n new line \` single qoute
\r carriage return \`` double qoute
\t horizontal tab \ooo octal number 0 o 7
\v vertical tab \xhh hex number h {0..9, A..F}

9
CSE, BUET CSE-105 Structured Programming
Constant : String (K R 2.3) n

String constant is a sequence of zero or more characters


surrounded by double quote. E.g.,
I am a string
/* the empty string */
String constants can be concatenated at compile time:
hello, world. hello, world.
This is useful for splitting long strings in several lines
String is an array of characters terminated by `\0`
Observe the difference between string and character constants
below:

hello, world.
h e l l o , w o r l d \0
0 1 .. 12
10
CSE, BUET CSE-105 Structured Programming
Constant : Usage (K R 2.3) n

Constant expression #define LO `A`


#define HI `Z`
Contains only constants int cap_count[HI-LO+1]
Can be evaluated in compile time.
A and `A` are not the same
A `A`
char v = `A` + 3; /* OK */
65 \0 65
char w = A + 3; /* Wrong */
Try these out:
printf(\b Alert is %d, `\b`);
printf(line is %c %d tested, `\n` , `\n`);
printf(Backspace h\bas effect );
printf (He said, \I am fine, thank %s.\, you);
11
CSE, BUET CSE-105 Structured Programming
Constant: Enumeration (K R 2.3) n

Enumerations are used to define multiple constants


Alternate to #define, but values are auto-generated.
Examples:
#define NO 0
enum { NO, YES };
#define YES 1

enum escapes { BELL = `\a`, BACKSPACE = `\b`, TAB = `\b`


NEWLINE = `\n`, VTAB = `\v`, RETURN = `\r`};

enum months { JAN = 1, FEB, MAR, APR, MAY, JUN,


JUL, AUG, SEP, OCT, NOV, DEC };
/* FEB is 2, MAR is 3, etc. */

12
CSE, BUET CSE-105 Structured Programming
Operators

CSE, BUET CSE-105 Structured Programming


Arithmetic Operators (K R 2.5) n

+ , , * , /, %
Division operator /
For ve operand, direction of truncation is m/c dependent
-7/2 = ? -3 or -4
Mod operator %
Cannot be applied on float or double
For ve operand, sign of result is m/c dependent
Precedence :
Highest : unary + and
2nd highest : * and /
Lowest : + and
Arithmetic operators associate left to right.
A * B * C = (A * B) * C

14
CSE, BUET CSE-105 Structured Programming
Relational & Logical Operators (K R 2.6) n

Relational Operators: > >= < <=


have lower precedence than arithmetic operators
thus, i < lim 1 i < (lim 1)
Equality Operators:
== !=
has lower precedence than Relational operators
Logical Operators: && || also !
Left to right associative
Evaluation stops as soon as truth or falsehood is known
Example follows
15
CSE, BUET CSE-105 Structured Programming
&& and || have short circuit evaluation
left operand evaluated first; right operand evaluated
only if necessary
&&: if left operand evaluates to 0, immediately
return 0
||: if left operand evaluates to nonzero value,
immediately return 1
This allows you to write code like this with
confidence:

if(y == 0 || x / y > MAX) ...

16 CS 3090: Safety Critical Programming in C 16


CSE, BUET CSE-105 Structured Programming
Relational & Logical Operators (K R 2.6) n

for (i=0; i<lim1 && (s[i]=getchar())!=`\n` && s[i]!=EOF; i++)


;

Condition in for loop is executed left to right


Array bound must be checked (i<lim-1) before s[i]=getchar( )
is executed
If the test i<lim-1 fails we cannot assign value to s[i]
Similarly it would be unfortunate to check s[i]!=EOF before
s[i]=getchar( ) is executed
Since precedence of != is higher than assignment parentheses
are needed in (s[i]=getchar())!=`\n`
s[i]=getchar()!=`\n` would be 1 or 0
DIY Ex. 2.2: Write a loop equivalent to above for loop without
using && or ||
17
CSE, BUET CSE-105 Structured Programming
Type Conversions (K R 2.7) n

Automatic conversions convert narrower operand into a wider


one.
Warnings are generated for expressions that may loose
information.
Binary operators (like +, *) with mixed operand types the lower
or narrower type is converted to higher or wider type.
long double > double > float > long int > short int > char.
unsigned > signed
-1L < 1U // 1U is promoted to signed long
-1L > 1UL // -1L is promoted to unsigned long
Explicit type conversion can be specified as follows
(type-name) expression

18
CSE, BUET CSE-105 Structured Programming
Type Conversions (K R 2.7) n

char can be used just like int.


/* atoi: convert s to integer*/
int atoi(char s[])
{
int i, n;

n = 0;
for (i = 0; s[i] >= `0` && s[i] <= `9`; ++i)
n = n * 10 + (s[i] - `0`);
return n;
}

/* lower: convert ct to lower case; ASCII only; */


int lower(int c)
{
if (c >= `A` && c <= `Z`)
return c + `a` - `A`;
else
return c;
}
19
CSE, BUET CSE-105 Structured Programming
Bitwise Operators (K R 2.9) n

Bitwise operators can only be applied to integral operands: i.e.,


all versions of char and int A B &
& : bitwise AND 0 0 0

Mask off some bits 0 1 0


1 0 0
n = n & 0177;
1 1 1
sets all bit of n to zero except the rightmost 7 bits
| : bitwise OR A B |
Turn on some bits 0 0 0
x = x | 0100; 0 1 1

Turns on the 6th (zero based) bit of x 1 0 1


1 1 1
Must be distinguished from && and || operators
int x = 1, y = 2; x && y 1 x || y 1
x&y0 x|y3
20
CSE, BUET CSE-105 Structured Programming
Example: setting a bit to one
value = value | 1 << bit_number;

0xAA | 1 << 2

10101010
00000100
10101110

21
CSE, BUET CSE-105 Structured Programming
Example: setting a bit to zero
value = value & ~ ( 1 << bit_number );

0xAA & ~ (1 << 3)

00001000
11110111
10101010
10100010

22
CSE, BUET CSE-105 Structured Programming
Bitwise Operators (K R 2.9) n

^ : bitwise XOR A B ^
0 0 0
Toggle (complements) some bits.
0 1 1
x = x ^ 0100; 1 0 1
Turns on the 6th (zero based) bit of x 1 1 0

~ : ones complement (unary) A ~


x = x & ~077; 0 1
Sets the last six bits of x to 0 1 0

Since sizeof(int) varies it is better than, x = x & 0177700


~ (bit-wise not) vs ! (logical not) operators
int x = 0;
~x -1
!x 1
23
CSE, BUET CSE-105 Structured Programming
Bitwise Operators (K R 2.9) n

<< : Left shift


x = x << 3;
Shifts x left by 3 bits x = x * 23
>> : Right shift
x = x >> 3;
Shifts x right by 3 bits x = x / 23
If x is unsigned then vacated bits are filled with 0
If x is signed then vacated bits are filled with 0 or 1
depending on the machine.

24
CSE, BUET CSE-105 Structured Programming
Bitwise Operators (K R 2.9) n

Application:
/* getbits: get n bits from position p*/
Unsigned getbits (unsigned x, int p, int n)
{
return (x >> (p+1-n)) & ~(~0 << n);
}

n=4, p=7 ~0 1111 ... 1111111111


... 9876543210
x 0110 ... 0101101011 ~0<<n 1111 ... 1111110000

x>>(p+1-n) 00000110 ... 010110 ~(~0<<n) 0000 ... 0000001111

(x>>(p+1-n))&~(~0<<n) 00000000 ... 000110

DIY: Exercise 2-6, 2-7, 2-8


25
CSE, BUET CSE-105 Structured Programming
Conditional Expressions (K R 2.11) n

if (a > b)
Only ternary operator ?: z = (a > b) ? a : b;
z = a;
else
expr1 ? expr2 : expr3; z = b;

The wider type of expr2 and expr3 is the results type


float f and int n
(n > 0) ? f : n will be float regardless of the value of
n
Example usage:
printf(You have %d item%s., n, n == 1 ? : s);

26
CSE, BUET CSE-105 Structured Programming
Assignment Operators : LValue vs RValue
LValue
It is the result of an expression that has an address
usually used at the left side of assignment operator ( = )
RValue
It is the result of an expression that has a vlaue
Usually used at the right side of assignment operator (=)
Example: LValue RValue
a = a + 10;
a: 48357 55

[48375] 55 + 10;
27
CSE, BUET CSE-105 Structured Programming
How x = y = z = 17 works?
= is right-associative so the expression is interpreted as:
x = ( y = ( z = 17 )

z is assigned 17;
return value is 17

y is assigned 17;
return value is 17

x is assigned 17;
return value is 17

28
CSE, BUET CSE-105 Structured Programming
= vs. ==
It is easy to confuse equality with assignment
In C, the test expression of an if statement can be
any int expression including an assignment
expression
Assignment performed;
y set to 0 (oops)
if (y = 0)
printf("Sorry, can't divide by zero.\n");
else Expression returns
result = x / y; result of assignment:
0, or "false"

else clause executed:


The compiler will not catch this bug! divide by 0!

29
CSE, BUET CSE-105 Structured Programming
Assignment Operators (K R 2.10) n

For binary operators there exists short hand of the


form:
+= = *= /= %= <<= >>= &= |= ^=
expr1 op= expr2 expr1 = (expr1) op (epxr2)
x *= y + 1 x = (x) * (y + 1)
Ease: yyval[yypv[p3+p4] + yypv[p1+p2]] += 2;
DIY : Exercise 2-9.
/* bitcount: count 1 bits in x */
Faster version of int bitcount (unsigned x)
{
bitcount using int b;
x &= (x 1) for (b = 0; x != 0; x >>= 1)
b += x & 1;
return b;
}
30
CSE, BUET CSE-105 Structured Programming
Assignment Operators (K R 2.10) n
x y

Swap two integers in one statement a b

x ^= y ^= x^= y;
x ^= y a^b b

y ^= x a^b a

x ^= y b a

Number of odd and even integers in input

31
CSE, BUET CSE-105 Structured Programming
Increment & Decrement Operators (K R 2.8) n

Unary ++ (increment) and unary -- (decrement)


Effect of Prefix and Postfix placement. (x++ vs. ++x)
At some places effect is same
if (c == `\n`) if (c == `\n`)
nl++; ++nl;
At some places it has different effect :
n = 5;
n = 5; x == 5
x = n;
x = n++; n == 6
n = n+1;

n = 5;
n = 5; x == 6
n = n+1;
x = ++n; n == 6
x = n;

32
CSE, BUET CSE-105 Structured Programming
Increment & Decrement Operators (K R 2.8) n

Effect of Prefix and Postfix placement. (x++ vs. ++x)


i = 4;
i = 4; s[4] == 8
s[i] = 8;
s[i++] = 8; i == 5
i = i+1;

i = 4;
i = 4; s[5] == 8
i = i+1;
s[++i] = 8; i == 5
s[i] = 8;

A more complicated example:

b = b + 1; a == 1
int a = 0, b = 0, c = 0;
c = a + b; c == 1
c = a++ + ++b;
a = a + 1; b == 1

33
CSE, BUET CSE-105 Structured Programming
Increment & Decrement Operators (K R 2.8) n

Proper application of these operators can produce


efficient and concise code:
/* strcat: concatenate t to end of s; s must be big enough */
void strcat(char s[ ], char t[ ])
{
int i = 0, j = 0;

while (s[i++] != `\0`) ; /* find end of s */


while ((s[i++] = t[j++]) != `\0`) ; /* copy t */
}

DIY:
Exercise: 2-4
Exercise: 2-5
34
CSE, BUET CSE-105 Structured Programming
Increment & Decrement Operators (K R 2.8) n

The operand of ++ and -- operator must have LValue


i++; // is ok
(i + j)++; // is not ok i: 48123 20
(i + j) has only RValue 50
(i = 0)++; // is ok j: 48567 30
i = 0 returns the LValue of I
(i = j + 2)++; // is ok
i = j + 2 i is assigned to (j + 2) and LValue of i is returned
then the i is incremented by 1
(i = j = 0) ++; // is ok
i = j = 0 i and j is assigned 0 and LValue of i is returned
i is then incremented by 1.
35
CSE, BUET CSE-105 Structured Programming
Precedence, Associativity & Evaluation order
Precedence: given two operators of different
types, which is evaluated first?
Associativity: given a sequence of instances
of the same operator, are they evaluated left-
to-right or right-to-left?
Evaluation order: given an operator with a
number of operands, in what order are the
operands evaluated?

36
CSE, BUET CSE-105 Structured Programming
Precedence (K R 2.12)n

Operators Associativity
() [] left to right

Uniary ! ~ ++ -- + - (type) sizeof right to left

Arithmetic * / % left to right


+ -
Shift << >> left to right

Higher Precedence
Relational < <= => > left to right
== !=
Bit-wise & left to right
^
|
Logical && left to right
||
Ternary ?: right to left

Assignment = += -= *= /= %= &= ^= |= <<= >>= right to left


37
CSE, BUET CSE-105 Structured Programming

Potrebbero piacerti anche