Sei sulla pagina 1di 36

Compsci 250 / ECE 250:

C Programming
Alvin R. Lebeck
Some slides based on those from Daniel Sorin,
Andrew Hilton, Amir Roth, Gershon Kedem

Administrivia
Homework #1
No class Monday
Today
! Finish Data Representations
! C programming & Memory

Updated Academic Honesty Policy


! Do not provide solutions to any archive (digital, paper, etc.)
! This is a simple extension of existing policy of not providing
solutions to another student.

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

Review: Answer
What floating-point number is
0xC1580000?
1100 0001 0101 1000 0000 0000 0000 0000
31 30

23 22

1 1000 0010 101 1000 0000 0000 0000 0000


S

Sign = 1 means this is a negative number


Exponent = (128+2)-127 = 3
Mantissa = 1.1011
-1.1011x23 = -1101.1 = -13.5

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

Special values in IEEE Floating Point


How do you represent 0.0 in IEEE Floating Point?
! 0.0 = 000000000
! But need 1.XXXXX representation?

Exponent = 0 is denormalized
! Implicit 0. instead of 1. in mantissa
! Allows 0000.0000 to be 0
! Helps with very small numbers near 0

Results in +/- 0 in FP (but they are equal )

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

Other Weird FP numbers


Exponent = 1111 1111 also not standard
! If all 0 mantissa: +/-

1/0 = +
-1/0 = -
! If non zero mantissa: Not a Number (NaN)

sqrt(-42) = NaN

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

FP Addition/Substraction
Addition/Subtraction
! Align the exponents
! Perform operation
! Renormalize the result (put into 1.M x 2E-127 form)

What can possibly go wrong?


Well a lot
Search for disasters caused by numerical errors

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

Software Implication! Rounding Errors


We only have 32-bits to represent floats
! Must approximate some values

Limited bits for mantissa


Does (x+y)*z = (x*z+y*z)?
Mathematically yes, but assumes infinite precision
Assume base 10, four digits available (two to left, two to
right of decimal point)
!
!
!
!

x = 99.96 x 103
x = x + 0.07
x = 100.03 x 103
x = 10.00 x 104

Numerical Analysis (CS 220) studies some of these


issues
Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

Floating Point Representation


Double Precision Floating point:
64-bit representation:
! 1-bit sign
! 11-bit (biased) exponent
! 52-bit fraction (with implicit 1).

double in Java, C, C++,

Exp

11-bit

Alvin R. Lebeck
From Sorin, Hilton, Roth

Mantissa
52 - bit

Compsci / ECE 250

Oct. Char
000
010
020
030
040
050
060
070
100
110
120
130
140
150
160
170

nul
bs
dle
can
sp
(
0
8
@
H
P
X
`
h
p
x

ASCII Character Representation


001
011
021
031
041
051
061
071
101
111
121
131
141
151
161
171

soh
ht
dc1
em
!
)
1
9
A
I
Q
Y
a
i
q
y

002
012
022
032
042
052
062
072
102
112
122
132
142
250
162
172

stx
nl
dc2
sub
"
*
2
:
B
J
R
Z
b
j
r
z

003
013
023
033
043
053
063
073
103
113
123
133
143
153
163
173

etx
vt
dc3
esc
#
+
3
;
C
K
S
[
c
k
s
{

004
014
024
034
044
054
064
074
104
114
124
134
144
154
164
174

eot
np
dc4
fs
$
,
4
<
D
L
T
\
d
l
t
|

005
015
025
035
045
055
065
075
105
115
125
135
145
155
165
175

enq
cr
nak
gs
%
5
=
E
M
U
]
e
m
u
}

006
016
026
036
046
056
066
076
106
116
126
136
146
156
166
176

ack
so
syn
rs
&
.
6
>
F
N
V
^
f
n
v
~

007
017
027
037
047
057
067
077
107
117
127
137
147
157
167
177

bel
si
etb
us
'
/
7
?
G
O
W
_
g
o
w
del

Each character represented by 7-bit ASCII code (packed into 8-bits)


Convert upper to lower case A + 3210 = a
Other tables with decimal and HEX values.
Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

Unicode
Many types
UTF-8: variable length encoding backward compatible
with ASCII
! Linux

UTF-16: variable length


! Windows, Java

UTF-32: fixed length

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

10

Data Representation Summary

Need efficient representations


2s complement for signed integers
IEEE Floating Point for Real numbers
Bits are bits are bits, same bits can be interpreted as
different types (unsigned, 2s complement, float, etc.)
Next up: C programming & memory

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

11

What you know today


JAVA
...
System.out.println("Please Enter In Your First Name: ");
String firstName = bufRead.readLine();
System.out.println("Please Enter In The Year You Were Born: ");
String bornYear = bufRead.readLine();
System.out.println("Please Enter In The Current Year: ");
String thisYear = bufRead.readLine();
int bYear = Integer.parseInt(bornYear);
int tYear = Integer.parseInt(thisYear);
int age = tYear bYear ;
System.out.println("Hello " + firstName + ". You are " + age + " years
old");

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

12

How does a Java program execute?


Compile Java Source to Java Byte codes
Java Virtual Machine (JVM) interprets/translates Byte
codes
JVM is a program executing on the hardware
Java has lots of things that make it easier to program
without making mistakes
JVM handles memory for you
! What do you do when you remove an entry from a hash table,
binary tree, etc.?

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

13

The C Programming Language


No virtual machine
! No dynamic type checking, array bounds, garbage collection, etc.
! Compile source file directly to machine (this is a little simplified)

Closer to hardware
! Easier to make mistakes
! Can often result in faster code

Generally used for systems programming


! operating systems, embedded systems, database implementation
! There is object oriented C++ (C is a strict subset of C++)

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

14

The C Programming Language (Continued)


No objects
Procedural, not object oriented
! No objects with methods

Structures, unions like objects


! Member variables (no methods)

Pointers memory, arrays


External standard library I/O, other facilities
Macro preprocessor (#<directive>)
Additional Resources
! Kernighan & Richie book The C Programming Language
! MIT open course Practical Programming in C link in docs of web
site
! Drew Hilton Video Snippets

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

15

Compiling and Running a C Program

Use the gcc program to create an executable file


gcc o <outputname> <source file name>
gcc o hello hello.c (must be in same directory as hello.c)
If no o option, then default output name is a.out (e.g., gcc hello.c)
Type the program name on the command line
! ./ before hello means look in current directory for hello program

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

16

Debugging
Print debugging
! Just output information at different points in the program
! Not the most efficient, but often works.

gdb <executable filename>


Good for stopping at set points in program and inspecting
variable values.
! If you get good at using a debugger it is easier/better than printf
debugging
! See GDB Essentials video off https://www.cs.duke.edu/courses/
spring15/compsci250/docs.html

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

17

Variables, operators, expressions


C variables are similar to Java
! Data types: int, float, double, char, void
! Signed and unsigned int
! char, short, int, long, long long can all be integer types
These specify how many bits to represent an integer

Constants
! Use #define C preprocessor
! E.g.,: #define MAX_SCORE 100

Operators:
! Mathematical +, -, *, /, %,
! Logical !, &&, ||, ==, !=, <, >, <=, >=
! Bitwise &, |, ~, ^ , <<, >> (well get to these next)

Expressions: var1 = var2 + var3;


Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

18

Bitwise AND / OR / XOR

& operator performs bitwise AND


| operator performs bitwise OR
^ operator performs bitwise Exclusive OR (XOR)
~ operator performs bitwise NOT

Per bit
0&0=0
0|0=0
0^0=0
0&1=0
0|1=1
0^1=1
1&0=0
1|0=1
1^0=1
1&1=1
1|1=1
1^1=0
For multiple bits, apply operation to individual bits in same position

AND
011010
101110
001010
Alvin R. Lebeck
From Sorin, Hilton, Roth

OR
011010
101110
111110

XOR
011010
101110
110100

Compsci / ECE 250

19

The SHIFT operator


>> is shift right, << is shift left, operands are unsigned int
and number of positions to shift
(1 << 3) is 000001 -> 0001000 (its 23)
0xff00 is 0xff << 8, and 0xff is 0xff00 >> 8
! Unsigned ints, be careful shifting signed integers (more later this
semester)

0xAB & 0x0F = 0x0B


0xAB & 0xF0 = 0xA0
0x0F and 0xF0 are called a bit mask

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

20

Sakai In Class Quiz 2.1


button
y
x
val = 01 1010 0011 0100 1100
32-bit word with x,y and button fields
!
!
!
!

bits 0-7 contain x position


bits 8-15 contain y position
bits 16-17 contain button (0 = left, 1 = middle, 2 = right)
Bits 18-31 dont matter

Which C Statements correctly set xpos, ypos & button?


A.
xpos = val && 0x000ff;
ypos = (val && 0x0ff00) >> 8;
button = (val && 0x30000) >> 16;

C.
xpos = val & 0x000ff;
ypos = (val & 0x0ff00) << 8;
button = (val & 0x30000) << 16;

Alvin R. Lebeck
From Sorin, Hilton, Roth

B.
xpos = val & 0x000ff;
ypos = (val & 0x0ff00) >> 8;
button = (val & 0x30000) >> 16;

D.
xpos = val & 0x000ff;
ypos = val & 0x0ff00 >> 1;
button = val & 0x30000 >> 2;

Compsci / ECE 250

21

Sakai In Class Quiz 2.1: Answer


button
y
x
val = 01 1010 0011 0100 1100
32-bit word with x,y and button fields
!
!
!
!

bits 0-7 contain x position


bits 8-15 contain y position
bits 16-17 contain button (0 = left, 1 = middle, 2 = right)
Bits 18-31 dont matter

Which C Statements correctly set xpos, ypos & button?


A.
xpos = val && 0x000ff;
ypos = (val && 0x0ff00) >> 8;
button = (val && 0x30000) >> 16;
Logical AND
C.
xpos = val & 0x000ff;
ypos = (val & 0x0ff00) << 8;
button = (val & 0x30000) << 16;
Shift wrong direction; value not
in least significant bits

Alvin R. Lebeck
From Sorin, Hilton, Roth

B.
xpos = val & 0x000ff;
ypos = (val & 0x0ff00) >> 8;
button = (val & 0x30000) >> 16;

D.
xpos = val & 0x000ff;
ypos = val & 0x0ff00 >> 1;
button = val & 0x30000 >> 2;
Precedenceshifts mask first; shift
amount wrong

Compsci / ECE 250

22

Functions
Encapsulate computation
! Reuse or clarity of code
! Cannot define functions within functions

Must be declared before use!


int div2(int x,int y); /* declaration here */
main() {
int a;
a = div2(10,2);
}
int div2(int x, int y) { /* implementation here */
return (x/y);
}

Or put functions at top of file (doesnt always work)


Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

23

Global Variables
Global variables: Accessible from any function
#include <stdio.h>
float f = 0;
void bar () {
f = 0.5;
}
int main()
{
f =0.31234;
bar();
printf(The value is %f \n, f);
}
Output is:
The value is 0.5

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

24

Memory Partitions
2n-1

Text for instructions

Stack

! add res, src1, src2


! mem[res] = mem[src1] +
mem[src2]

Typical
Address
Space

Data
! static (constants, global variables)
! dynamic (heap, malloc / new
allocated)
! grows up

Heap

Stack

Data

! local variables
! grows down

Text

Variables are names for


memory locations

Reserved

! int x;
Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

25

A Simple Programs Memory Layout


...
int result; // global var
int main()
{
int x;
...
result = x + result;
...
}
For now, think of this as performing:
mem[0x208] = mem[0x400] + mem[0x208]

2n-1

x 0x400

Compsci / ECE 250

Heap

result 0x208

Data
3

Text
0

Alvin R. Lebeck
From Sorin, Hilton, Roth

Stack

Reserved

26

Sakai In Class Quiz 2.2


#include <stdio.h>
int a = 0;
float f = 0.5;
void setvals() {
float f = 0.5;
a = 78;
}
int main()
{
int a = 23;
f =0.31234;
setvals();
printf(The values are %d, %f \n,a,f);
}

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

What is the result?


a)
b)
c)
d)

a = 78, f = 0.5
a = 78, f = 0.31234
a = 23, f = 0.5
a = 23, f = 0.31234

27

Sakai In Class Quiz 2.2


#include <stdio.h>
int a = 0;
float f = 0.5;
void setvals() {
float f = 0.5;
a = 78;
}
int main()
{
int a = 23;
f =0.31234;
setvals();
printf(The values are %d, %f \n,a,f);
}

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

2n-1

a 0xF0020
f 0x F0000

Stack

Heap
f 0x20004
a 0x 20000

Data
Text

Reserved

28

Reference vs. Pointer


Java
! The value of a reference type variable, in contrast to that of a
primitive type, is a reference to (an address of) the value or set of
values represented by the variable http://java.sun.com/docs/books/tutorial/java/
nutsandbolts/datatypes.html

! Cannot manipulate the value of the reference

C
! A pointer is a variable that contains the location of another
variable
! A pointer is a memory location that contains the address of
another memory location
! Can manipulate the value of pointer (double edge sword)

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

29

Pointers
Declaration of pointer variables
! int *x_ptr; char *c_ptr; void *ptr;

How do we get the location (address) of a variable?


Use one of the following:
1. Use the & address of operator
!

x_ptr = &intvar;

2. From another pointer (yes we can do arithmetic on them)


!

x_ptr = y_ptr + 18;

3. Return from memory allocator


!
!

x_ptr = (int *) malloc(sizeof(int));


Similar to java new, but must explicitly free memory (i.e., free(x_ptr));

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

30

Pointers
address of operator &
! don t confuse with bitwise AND operator
Given
int x; int* p; // p points to an int
p = &x;
Then
*p = 2; and x = 2; produce the same result
Note: p is a pointer, *p is an int

What happens for p = 2?;


On 32-bit machine, p is 32-bits

x 0x26cf0

...

p 0x26d00 0x26cf0

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

31

Pointers
De-reference using *ptr to get what is pointed at
statement

x_ptr

int x;

??

??

int *x_ptr;

??

??

x=2

??

x_ptr = &x;

&x

*x_ptr = 68;

68

&x

x_ptr = 200;

68

200

*x_ptr = 42

68

200

Be careful with assignment to a pointer variable


! You can make it point anywherecan be very bad
! You will, this semester, likely experience a segmentation fault
! What is 200?
Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

32

Sakai In Class Quiz 2.3


Which Version Correctly Swaps Values?
void swap (int x, int y){
int temp = x;
x = y;
y = temp;
}
main() {
int a = 3;
int b = 4;
swap(a, b);
printf(a = %d, b= %d\n,
a, b);
}

void swap (int *x, int *y){


int temp = *x;
*x = *y;
*y = temp;
}
main() {
int a = 3;
int b = 4;
swap(&a, &b);
printf(a = %d, b= %d\n,
a, b);
}

A.

Alvin R. Lebeck
From Sorin, Hilton, Roth

B.

Compsci / ECE 250

33

Strings as Arrays
s t
0 1

r i
15 16

g \0
42 43

A string is an array of characters with \0 at the end


Each element is one byte, ASCII code
\0 is null (ASCII code 0)
char str1[256] is similar to str2 = (char *) malloc(256);

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

34

Structures
Loosely like objects
! Have member variables
! Do not have methods!

Structure definition with struct keyword


struct student_record {
int id;
float grade;
} rec1, rec2;

Declare a variable of the structure type with struct keyword


struct student_record onerec, *tworec;

Access the structure member fields with


! . structvar.member (e.g., onerec.id = 12;)
! -> structprt->member (e.g., tworec->id;)

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

35

Summary
C is different from Java
! Procedural
! Structures not objects
! Pointers!

Next time
! Explicit memory deallocation
! Pointer manipulation
! Linked Structures

Alvin R. Lebeck
From Sorin, Hilton, Roth

Compsci / ECE 250

36

Potrebbero piacerti anche