CS 136

Elementary Algorithm Design and Data Abstraction

Instructor: Navid Esfahani Section: 10 / Tuesday/Thursday (4:00-5:20 or 2:30-3:50) Email: nnasresf@uwaterloo.ca Website: http://www.student.cs.uwaterloo.ca/~cs136/ Office: DC 2127 Office Hours: Thursday 8:30 - 10:30 am Lab Hours: MC 3004 / (12-5 pm on Fridays) Textbook: Course Notes Midterm: Final:

7/1/20

Main topics & themes:

Programming environment (Seashell)
customized "Seashell" development environment.

Course Materials
Textbooks

Course notes

Go to tutorials to learn

Marking scheme

participation grading

Assignments:

Documentation:

9/1/20

C was developed by Dennis Ritchie in 1969-1973 to make the Unix operating system more portable.

C versions There a few different versions of the C standard. In this course, we use C99 (from 1999).

C Syntax Intro

Comments any text on a line after // is a comment. Any text between /* and */ is also a comment.
Note: C's multi-line comment cannot be "nested":

/* this /* nested comment is an */ error */

Expressions: C expressions use traditional infix algebraic notation (ex: 3 + 3)
1 + 3 * 2   ⟹  \implies 7
(1 + 3) * 2   ⟹  \implies 8

Operators: In addition to the traditional mathematical operators, c also has non-mathematical operators. With over 40 operators in total (CP:AMA Appendix A).

The / operator

The % operator: the C modulo operator produces the remainder after integer division
The value of (a % b) is equal to a - (a / b) * b

C identifiers: Ever function, variable, and structure requires an identifier (or "name").

Anatomy of a function definition

int my_add(int a, int b) { return a + b; }

Static typing system: C uses a static type system: all types must be known before the program is run and the type of an identifier cannot change.

If the type in a function definition is missing C assumes it to be an int:

int my_add(int a, int b) { //Proper return a + b; } my_add(a , b){ return a + b; }

Function terminology: We call a function by passing it arguments, a function returns a value.

Functions without parameters:

use the void keyword to indicate a function has no parameters.

int my_num(void) { return my_add(40,2); }

C allows the omission of void which indicates an "unknown" or "arbitrary" number of parameters (beyond the scope of this course). Always use void.

No nested function: In C we are not able to define nested functions. This feature was added to the GNU C compiler but is not found in C Standard.

int top(void) { int nested_func(void) { //... // This is not possible } }

Function Documentations

Whitespaces C mostly ignores whitespace.

// The following three functions are equivalent int my_add(int a, int b) { //Good return a + b; } int my_add(int a, int b) { return a + b; //Bad } int my_add(int a, int //Very bad b){return a+ b ; }

CS 136 style:

int my_add(int a, int b) { //Good return a + b; }
int my_super_long_function(int a, int b, int c, int d, int e, int f, int g) { return a * b + b * c + c * d + d * e + d + d * e d + e; }

Entry point: Typically a program is run by an Operating System (OS) through a shell or another program such as DrRacket. The SO needs to know where to start running the code.

main: main has no parameters (for now) and int return type.

int main(void) { //... return 0; }

14/1/20

Top level expressions: In C, top-level expressions (code outside of a function) are not allowed.

1 + 1; // INVALID int my_add(int a, int b){ return a + b; }

Tracing expressions: Seashell provides tracing tools to help you "see" what your code is doing. trace_int is a function that allows you trace integers.

int main(void){ trace_int(1 + 1); trace_int(my_add(1,2)); }

Running our first program

// First C program (documentation omitted) #include "cs136.h" // <-- More on this later int my_add(int a, int b){ return a + b; } int main(void){ trace_int(1+1); trace_int(my_add(1,2)); return 0; }

Function ordering:

Program documentation:

Testing:

Boolean expressions:

Comparison operators:

The equality operator in C is == (not the double equals)
(3 == 3) ⇒\Rightarrow 1 (true)
(2 == 3) ⇒\Rightarrow 0 (false)
The not equal operator is !=
(2 != 3) ⇒\Rightarrow 1 (true)

The operators <, <=, > and >= behave exactly as expected.

Logical Operators:

The logical operators are ! (not), && (and), || (or):

Similarly to Racket, C short-circuits and stops evaluating logical operators as soon as possible.

All non-zero values are true:

Operator Symbol
Negations !
multiplicative * / %
additive + -
comparison < <= >= >
equality == !=
and &&
or ||

Bool type

The bool type is an integer that can only have a value 0 or 1.

bool is_even(int n) { return (n % 2) == 0; } bool my_negate(bool v) { return !v; }

Assertion

use the assert function to test functions:

assert(my_add(1,2) == 3);

assert(exp) stops the program and displays a message if the expression exp is false (zero).

if exp is true (non-zero), it does "nothing" and continues to the next line of code.

// My second C program (now with better testing!) #include "cs136.h" int my_add(int a, int b) { return a + b; } int main(void){ assert(my_add(1,2)==3); assert(my_add(2,2)==4); }

Function requirements

The assert function is also very useful for verifying function requirements.

// my_divide(x, y) ... // requires: y is not 0 int my_divide(int x, int y) { assert(y!=0); return x/y; }

Infeasible requirements

Some requirements are infeasible to assert, or they would be inefficient to assert.
It is good style to communicate that a requirement is not asserted

// some function ... // requires: n is a prime number [not asserted]

Multiple requirements

With multiple requirements, it is better to have several small asserts. It makes it easier to determine which assertion failed.

// int my_function (int x, int y, int z) { assert((x > 0) && (y < z)); }

Statements

Blocks ({}) can contain multiple statements:

int my_divide(int x , in y) { assert(y) // statement trace_int(y) // statement return x / y; // statement trace_int(x); // unreachable statement }

Statements are executed in sequence (on after the other).
The return statement ends the function. In the above code, trace_int(x) will never run.

Brief introduction to control flow

The return statement is a special kind of statement known as a control flow statement.
return "controls the flow" of the program by ending the function and returning to the caller.

Conditionals

The if control flow statement allows us to have functions with conditional behaviour.

int my_abs(int n) { if (n < 0) { // note: the () are required return -n; } else { // In CS136 they have else on the same line on the closing } return n; } }

else if

if there are more than wo possible results, use else if

// in_between(x, lo, hi) determines if lo <= x <= hi // requires: lo <= hi bool in_between(int x, int lo, int hi) { assert(lo<=hi); if (x < lo) { return false; } else if (x > hi) { return false; } else { return true; } }

The C ternary conditional operator (?:)

q ? a : b
(v >= 0) ? v : -v; // abs(v) (a > b) a : b; // max(a, b)

Goals of this section

Introduction to imperative C

Readings: CP:AMA

Functional programming

In the imperative programming paradigm functions may be "impure" and will use variables

Compound statement

In imperative programming, a sequence of instructions (or "statements") are executed. We have already seen this:

int main(void) { trace_int(1+1); assert(3 > 2); return 0; }

A block {} is formally known as a compound statement, which is simple a sequence of statements to be executed in order

I/O (input/output)

Text I/O

To displace text output in C, we use the printf function.

// My first program with I/O #include "cs136.h" int main(void) { printf("Hello, World"); }

16/1/20

Text I/O ...

The newline character (\n) is necessary to properly format output to appear on multiple lines

To output values, use a format specifier (the f in printf).

printf("2 + 2 is %d",2+2); printf("%d + %d is: %d\n",2,2,2+2); // 2 + 2 is: 4

If you would like to print a percent sign (%), use two (%%).

printf("I am %d%% sure you should watch your",100); // I am 100% sure you should watch your printf("spacing!\n");

Similarly,

Side effects and state (introduction)

In general, a programming side effect is when the state of something "changes".
State refers to the value of some data (or "information") at a moment in time.

Documenting side effects

The printf function has a side effect: it changes the output or "display"

// noisy_abs(n) computes |n| // effects: may produce output int noise_abs(int n) { if (n < 0) { printf("Yo! I'm changing the sign!\n"); return -n; } else { return n; } }

In this course there is no need to provide any detail in the "effects" section // effects: produces output is sufficient.

Debugging tools

Statement used for debugging and informal testing (assert, trace_int) are not considered side effects.

I/O terminology

In the context I/O, be careful with eerminoloy.

int sqr(int n) { return n * n; } int noise_sqr(int n) { printf("Yo! I'm squaring %d!\n",n); return n * n; }

Our tracing tools print to a different output stream than printf (like writing on two different pieces of paper). By default printf outputs to stdout (standard output stream). Our tracing tools print to stderr (standard error stream).

Void functions

// Display score: produces score // Effects produces output void display_score(int score, int max) { printf("your score is %d out of %d.\n", score, max) }

Expression statements

An expression statement is an expression with a semicolon (;)

int main(void) { 11; 10 + 1; sqr(6) - sqr(5); printf("expression\n"); printf("five\n")+6; }

Return value of printf

Surprisingly printf is not a void function it (returns an int)

Statements

Variables

Variables store values To define a variable in C, we need (in order):

int my_variable = 7; // definition

Definitions are not statements.

Mutation

When the value of a variable is changed, it is known as mutation

int main(void) { int m = 5; trace_int(m); // definition (with initialization) m = 6; trace_int(m); // mutation! m = -1; trace_int(m); // more mutation! }

Mutation is a side effect

Assignment operator

In C, mutation is achieved with the assignment operator (=)

m = m + 1;

Pro tip: some defensive programmers get in the habit of writing equalities as (13 == i) this makes it so that if one equals is missed it produces an error rather than being a bug.

Initialization

C allows a variable definition without initialization, but is bad style.

int my_variable = 7; // initialized int another_variable; // uninitialized

Initialization is not assignment

int n = 5; // initialization syntax n = 6; // assignment operator

More assignment operators

x += 2; // x = x + 2; ++x; x++; // x += 1;

21/1/20

Constants

A constant is a variable that is immutable. In other words, the value of a constant cannot be changed.

const int my_constant = 42

It is good style to use const as much as possible (whenever it is appropriate):

Global and local variables

Variables are either global or local

int my_global_variable = 7; void f(void) { int my_local_variable = 11; //... }

Variable Scope

The scope of a variable is the region of code where it is accessible

Block (local scope)

Local variables have block scope. their scope extended from their definition to the end of the block they are defined in.

int n = 1; int main(void) { trace_int(n); // n => 1 int n = 2; trace_int(n); // n => 2 { int n = 3; trace_int(n); // n => 3 } trace_int(n); // n => 2 }

In older versions of C all local variable definitions had to be at the start of a function block (before any statements). In C99 you may define a local variable anywhere in a block.

Modern programming guides recommend that you define a variable:

int a = 2; int f() { int n = 3; // Here } int b = 5; int main() { int v = 3; f(); }

"Impure" functions

Recall that the functional paradigm requires "pure" functions:

Impure functions are sometimes called "procedure" or "routines" to distinguish behaviour from "pure" functions

Mutating global variables

A function that mutates a global variable has a mutation side effect (which makes it "impure").

Mutating parameters

Parameters are nearly indistinguishable from local variables, and can also be mutated.

Global dependency

A function that depends on a global mutable variable is "impure" even it has no side effects.

A "pure" function only depends on its argument values.

Avoiding global mutable variables

Global mutable variables are almost always poor style and should be avoided.
Unless otherwise specified, you are note allowed to use global mutable variable on your assignments.
On the other hand, global constants are great style and strongly encouraged.

Static local variables

Have the scope of a local variable, but the duration of a global variable. Their value persists between function calls.

int increment(void) { static int counter = 0; counter += 1; return counter; }

Like global mutable variables, they are almost always poor style and should be avoided. They are not allowed in this course.

Text input

The converse of printf is scanf, but we are not going to use it yet.

Read helper functions

In this course we have provided some helper functions to make reading in input easier. For example: read_int() reads an integer

Input formatting

When C read in int values, it skips over any white spaces

Reading input

Testing harness

To summarize our function testing strategies:

void test_sqr(void) { int n = read_int(); if (n != READ_INT_FAIL) { printf("%d", sqr(n)); test_sqr(); } }

Goals of this section

You should be able to answer all of the following:

C Model: Memory & Control Flow

Models of computation

In this course, we model the behaviour of C with two complimentary mechanisms

Control flow

We use control flow to model how programs are executed.
During execution, we keep track of the program location, which is "where" in the code the execution is currently occurring.
When a program is "run", the program location starts at the beginning of the main function.

Types of control flow

Return

return changes the program location to go back to the most recent calling function. Obviously C needs to keep track of where it is, we discuss this more later on in the course.

Conditionals

The syntax of if is

if (expression) statement

where the statement is only executed if the expression is true

if (n > 0) printf("n is positive");

The if statement only affects whether the next statement is executed. This is why if statements work without curly braces if it is only one statement (the curly braces are what allow more than one statement to be ignored).

23/1/20

Clarifications:

Flowchart basics

Braces are sometimes necessary to avoid a "dangling" else.

if (y > 0) if (y != 7) printf("you lose"); else printf("you win!"); // when does this print

Switch statements

int a = 5; switch(a) { case 0: printf("Won't print this"); case 5: printf("Will print this"); case 4: print("also this..."); default: print("and this..."); }

C goto

if (k < 0) goto mylabel; // ... mylabel: //...

Looping

With mutation, we can control flow with a method known as looping

while (expression) statement

while is similar to if: the statement is only executed if the expression is true.

The difference is, while repeatedly "loops back" and executes the statement until the expression is false

Iteration vs. recursion

Using a loop to solve a program is called iteration

Iteration is an alternative to recursion and is much more common in imperative programming.

// recursion int sum(int k) { if (k <= 0) { return 0; } return k + sum(k - 1); } // iteration int sum(int k) { int s = 0; while (k > 0) { s += k; --k; } return s; }

Tracing tools

trace_int() traces an integer even through loops and will state when a loop has started and the value of the integer for each iteration

do ... while

the do control flow statement is very similar to while

do statement while (expression);

The difference is that statement is always executed at least once, and the expression is checked at the end of the loop

do { printf("try to guess my numebr! \n"); guess = read_int(); } while (guess != my_number && guess != READ_INT_FAIL);

break

The break control flow statement is useful to exit from the middle of a loop

break is

continue

The continue control flow statement skips over the rest of the statements in the current block and "continues" with the loop.

For loops

The final control flow statement we introduce for, which is often referred to as a "for loop".

for loops are a "condensed" version of a while loop.

for (int i = 0; i < 10; ++i) { printf("%d",i;) }
// counting up from 0 to n-1 for ( i = 0; i < n; ++i) {...} // counting up from 1 to n for (i = 1; i <= n; ++i) {...} // counting down from n-1 to 0 for (i = n - 1; i >= 0; --i) {...} // counting down from n to 1 for (i = n; i > 0; --i) {...}

any of the three components of a for statement can be omitted. If the expression is omitted, it is always "true".

28/1/20

Memory Review

One bit of storage (in memory) has two possible states: 0 or 1
A byte is 8 bits of storage. Each byte in memory is in one of 256 (282^8) states.

Accessing memory

The smallest accessible unit of memory is a byte.
To access a byte of memory, its position in memory, which is known as the address of the byte, must be known.
For example, if you have 1 MB of memory (RAM), the address of the first byte is 0 and the address of the last byte is 1048575=(220−1)1048575 = (2^{20} - 1).

Note: Memory address are usually represented in hex, so with 1 MB of memory, the address of the first byte is 0x0, and the address of the last byte is 0XFFFFF.

Defining variables

For a variable definition in C:

In CS 135 we viewed variables as a "name for a value", but we now view variables as "name for a location" where the values are stored.

sizeof

When we define a variable, C reserves space in memory to store its value, but how much space is require?

The size operator (sizeof) produces the number of bytes required to store a type (it can also be used on identifiers). sizeof looks like a function, but it is an operator.

Integer Limits

C uses 4 bytes (32 bits) to store an int, there are only 2322^{32} possible values that can be represent.
The range of C int values is −231⋯(231−1)-2^{31} \cdots (2^{31}-1) or −2,147,488,648⋯2,147,483,647-2,147,488,648 \cdots 2,147,483,647. In our environment, the constants INT_MIN and INT_MAX are defined as those limits.

Overflow

if we try to represent values outside of int limits, overflow occurs.

The char type

The char type is also used to store integers, but C allocates one byte of storage for a char (an int has 4 bytes).
The are 282^8 possible values for a char (−128⋯127-128 \cdots 127 in seashell environment)

ASCII

ASCII was developed when teletype machines were popular, most modern applications have moved to unicode

C characters

in C, single quotes (') are used to indicated an ASCII character.
For example, a is equivalent to 97 and z is 122.
In C, there is no difference between the two variables.

char letter_a = 'a'; char ninety_seven = 97; printf("%c \n", ninety_seven) // prints a printf("%d \n", letter_a) // prints 97

Character arithmetic

Because C interprets characters as integers, characters can be used in expressions to avoid having "magic numbers" in your code.

bool is_lowercase(char c) { return (c >= 'a') && (c <= 'z'); } char to_lowercase(char c) { if ((c >= 'A') && (c <= 'Z')) { return c - 'A' + 'a'; } else { return c; } } char to_uppercase(char c) { if((c >= 'a') && (c <= 'z')) { return c - 'a' + 'A'; } else { return c; } }

read_char()

the same as read_int() but for char

Symbol type

C symbols are constants (often int) which are usually defined in all caps

const int UP = 1;

Floating point types

The C float can represent real (non-integer) values.

float pi = 3.14159; float avogadro = 6.022e23;
float penny = 0.01; float money = 0; for (int i = 0; i < 100; ++i) { money += penny; } // value of money is 0.999999

In C, a float is 8 bytes, one byte is for the exponent (−127⋯128-127 \cdots 128), one bit is for the sign, leaving 23 bits, so the precision is 2322^{32}

Structures

Structures (compound data) in C are similar to structures in Racket.

struct posn { // name of the structure int x; // type and field names int y; }; // don't forget this ;

the structure type includes the keyword "struct". For the example aboce the type is struct posn not just posn.

struct posn p = {3, 4}; // note the use of {} trace_int(p.x);

Mutating with structures

struct posn p = {1, 2}; struct posn q = {3, 4}; p = q; // p = {3, 4} p.x = 23; // p = {23, 4}

The braces are part of the initialization syntax and can not be used in assignment.

struct posn p = {1, 2}; p = {3, 4}; // INVALID p.x = 3; // VALID p.y = 4;

The equality operator (==) does not work with struct

Structures in the memory model

For a structure definition, no memory is reserved:

struct posn { int x; int y; };

Memory is only reserved when a variable is defined:

struct posn p = {3, 4};

30/1/20

Sizeof a struct

struct mystruct { int x; // 4 bytes char c; // 1 byte int y; // 4 bytes };

the amount of space reserved for a struct is at least the sum of the sizeof each field, but it may be larger.

trace_int(sizeof(struct mystruct)); // sizeof(struct mystruct) => 12

Sections of memory

In this course we model five sections ("regions") of memory.

Sections
Code
Read-only data
Global data
Heap
Stack

Temporary results

When evaluating C expressions, the intermediate results must be temporarily stored.

a = f(3) + g(4) - 5;

The code section

When you program you write source code in a text editor using ASCII characters
To "run" a C program, the source code must be converted into machine code that is machine readable
This machine code is then placed into the code section of memory

converting source code into machine code is known as compiling

The read-only & global data sections

Earlier we described how C reserves space in memory for a variable definition
All global variables are placed either in the global variables section or the read only section

The return address

When we encounter a return, we need to know: "what was the address we were at right before this function was called?"

In this course, we use the name of the calling function and a line number (or an arrow) to represent the return address

The call stack

The "history" of function calls (say function f,g,h are called in main) are stored in the call stack

Stack frames

"entries" pushed onto the call stack are known as stack frames
Each function call creates a stack fram ("fram of reference")
Each stack frame contains:

C makes a copy of each argument value and places the copy in the stack frame

Although space is reserved for global variables before the program is executed, space for local variables is only reserved when the function is called

Example stack frame:

int h(int i) { int r = 10 * i; return r; } int g(int y) { int c = y * y; return c; } int f(int x) { int b = 2*x + 1; int d = g(b + 3) + h(b); return d; } int main(void) { int a = f(2); //... } // Stack frame ========================= g: y: 8 c: 64 return address: f:13 ========================= f: x: 2 b: 5 d: ??? return address: main:18 ========================= main: a: ??? return address: OS =========================

Calling a function

We can now model all of the control flow when a function is called:

return

When a function returns:

Recursion in C

In C, each recursive call is simply a new stack frame with a separate frame of reference. The only unusual aspect of recursion is that the return address is a location within the same function.

Stack section

The call stack is stored in the stack section, the fourth section of our memory model. We refer to this section as the "the stack".
The "bottom" of the stack (where the main stack frame is placed) is placed at the highest available memory address. Each additional stack frame is then placed at increasingly lower address. The stack "grows" toward lower address.

Uninitialized memory

Global variables are initialized with a value of 0 in C, local variables are initialized with a random value.

void mystery(void) { int k; printf("the value of k is: %d\n", k); }

Memory snapshot

You may be asked to draw a memory diagram (including the call stack) at a particular moment in the code execution.

When a variable is defined inside of a loop, only one occurrence of the variable is placed in the stack frame. The same variable is re-used for each iteration.
Each time the definition is reached in the loop, the variable is re-initialized (it does not retain its value from the previous iteration)

Goals of this section

At the end of this section

4/2/20

Introduction to Pointers in C

Address operator

C was designed to give programmers "low-level" access to memory and expose the underlying memory model.

The address operator (&) produces the location of an identifier in memory (the starting address of where its value is stored)

int g = 42; int main(void) { printf("the value of g is: %d\n", g); printf("the address of g is: %p\n", &g); } // the value of g is: 42 // the address of g is: 0x71a0a0

Pointers

In C, there is also a type for storing an address: a pointer

a pointer is defined by placing a (*) before the identifier (name). The * is part of the definition syntax, not the identifier itself.

int g = 32; int i = 42; int *p = &g; // p "points at" i p = &i; // i => 42 // &i => 0xf020 // p => 0xf020 // &p => oxf024

The type of p is an "int pointer" which is written as "int *".

For each type (e.g, int, char) there is a corresponding pointer type (e.g, int *, char *)

When drawing a memory diagram, we rarely care about the value of the address, and visualize a pointer with an arrow (that "points")

sizeof a pointer

Int most k-bit systems, memory address are k bits long, so pointers require k bits yo store an address

Indirection operator

The indirection operator (*), also known as the deference operator, is the inverse of the address operator (&).

int i = 42; int *p = &i; // p => 0xf020 // *p => 42

Pointers to pointers

"Can a pointer point at itself?"

int *p = &p; // pointer p points at p ???

In C, we can define a pointer to a pointer:

int i = 42; int *p1 = &i; // pointer p1 points at i int **p2 == &p1; // pointer p2 points at p1

A void pointer (void *) can point at anything, including a void pointer (itself)

Dereferencing pointers to structures

The structure operator (.) has higher precedence than the indirection operator (*)

Awkward parenthesis are required to access a field of a pointer to a structure

(*ptr).field

Fortunately, the indirection selection operator, also known as the "arrow" operator (->) combines the indirection and the selection operators.

ptr->field is equivalent to (*ptr).field

The NULL pointer

NULL is a special pointer value to represent that the pointer points to "nothing"

If the value of a pointer is unknown at the time of definition, or what the pointer points at becimes invalid, it's good style to assign the value of NULL to the pointer. A pointer with a value of NULL is often known as a "NULL pointer"

The following two are equivalent:

if (p) ... if (p != NULL)
p = NULL; i = *p; // crash!

Pointer assignment

int i = 5; int j = 6; int *p = &i; int *q = &j; p = q;

This is an example of aliasing, which is when the same memory address can be accessed from more than one variable

6/2/20

Mutation and parameters

Pass by value:
copy of an argument is passed to a function, so the function cannot change the original value. The alternative to this is "pass by reference"

In C, we can emulate "pass by reference" by passing the address of a variable.

It is also common to say pass a pointer

void inc(int *p) { *p += 1; } int main(void) { int x = 5; trace_int(x); inc(&x); // note the & trace_int(x); }

Most pointer parameters should be required to be valid (e.g., non-NULL)

// inc(p) increments the value of *p // effects: modifies *p // requires: p is a valid pointer void inc(int *p) { *p += 1; }

Documenting the side effect

We now have a fourth effect that a function may have:

// effects: modifies *px and *py void swap(int *px, int *py) { int temp = *px; *px = *py; *py = temp; }

C input: scanf

scanf requires a pointer to a variable to store the value read from input.
Just like printf, scanf can be used to read in more than one value

scanf return value

The return value of scanf is an int, and either:

Invalid input

retval = scanf("%d", &i); // read in an integer, store it in i if (retval != 1) { printf("Fail! I could not read in an integer!\n"); }

Whitespace

// reads in next character (may be whitespace character) count = scanf("%c", &c); // reads in next character, ignoring whitespace count = scanf(" %c", &c); // This is better count = scanf("\n%c", &c);

Using pointers to return multiple values

Functions in C can only have one return value, we can use pointers to emulate returning more than one value.

void divide(int num, int denom, int *quot, int *rem) { *quot = num / denom; *rem = num % denom; }

This multiple return is also useful for when a function could encounter an error.

bool divide(int num, int denom, int *quot, int *rem) { if (denom == 0) return true; *quot = num / denom; *rem = num % denom; return false; }

Returning an address

A function must never return an address within its stack fram.

int *bad_idea(int n) { return &n; // Never do this } int *bad_idea2(int n) { int a = n*n; return &a; }

Passing structures

When a function is called, a copy of each argument value is placed into the stack frame.

For structures, the entire structure is copied into the stack frame. For large structures, this can be quite inefficient.

To avoid structure copying, it is common to pass the address of a structure to a function

// sqr_dist(p1, p2) calculates the square of // the distance between p1 and p2 int sqr_dist(struct posn *p1, struct posn *p2) { int xdist = p1->x - p2->x; int ydist = p1->y - p2->y; return xdist * xdist + ydist * ydist; }

passing the address of a structure allows the function to mutate the fields of the structure.

// scale(p, f) scales the posn p by f // requires: p is not null // effects: modifies p void scale(struct posn *p, int f) { p->x *= f; p->y *= f; }

Const pointers

Adding the const keyword to a pointer definition prevents the pointer’s destination from being mutated through the pointer.

void cannot_change(const struct posn *p) { p->x = 5; // INVALID }

Place const before the type

Const parameters

void can_change(struct posn *p) { p->x = 5; // VALID } void cannot_change(const struct posn *p) { p->x = 5; // INVALID }

Const parameters could be used with simple variables as well

int my_function(const int x) { // mutation of x here is invalid // ... }

It does not matter if the original argument is a constant because

Minimizing mutative side effects

Your preference for function design should be:

  1. “Pure” function
  1. Only I/O side effects
  2. Mutate data through pointer parameters
  3. Global dependencies
  4. Mutate global data

Function pointers

In Racket, functions are first-class values.

For example, Racket functions are values that can be stored in variables and data structures, passed as arguments and returned by functions.

In C, functions are not first-class values, but function pointers are.

A significant difference is that new Racket functions can be created during program execution, while in C they cannot.

The function pointer stores the starting address a function in code section of memory.

The type of a function pointer includes the return type and all of the parameter types, which makes the syntax a little messy.

return_type (*fpname)(param1_type, param2_type, ...)

Example:

int my_add(int x, int y) { return x + y; } int my_sub(int x, int y) { return x - y; } int main(void) { int (*fp)(int, int) = NULL; fp = my_add; trace_int(fp(7, 3)); fp = my_sub; trace_int(fp(7, 3)); } // fp(7, 3) => 10 // fp(7, 3) => 4

11/2/20

double constant (double x) { return 1; } double linear (double x) { return x; } double square (double x) { return x*x; } double cube (double x) { return x*x*; } double R_sum (double (*fp) (double), double a, double b, double delta) { double sum = 0; for (double i = a; i < b; i += delta) { sum += delta * fp(i); } return sum; }

Modularization & ADTs

Modularization

A module provides a collection of functions that share a common aspect or purpose

Modules vs. files

In this course, and in most cases, it is considered good style to store modules in separate files.

Terminology

The client requires the functions that a module provides

Building a program

When building a program we can combine ("link") multiple machine code files together to form a single program. that means we can "build" a program from multiple source code files and/or machine code files

main.c module.c module2.c module3.ll

Motivation (benefits of modularization)

Re-usability: A good module can be re-used by many clients. Once we have a "repository" of re-usable modules, we can construct large programs more easily.

Maintainability: It is much easier to test and debug a single module instead of a large program. If a bug is fond only the module that contains the bug needs to be fixed.

Abstraction: To use a module, the client needs to understand functionality it provides, but it does not need to understand how it is implemented.

Declarations

In C, a function or variable mus tbe declared before it can b accessed (or referenced)

A variable declarations starts with extern keywords, followed by the type then the variable name. There is no initialization

extern int g; void printg(void) { print("%d",g); } int main() { int g = 9; printg(); }

Module scope

To "hide" a global identifier from other files, prefix the definition with the static keyword

In other words, the static keyword restricts the scope of a global identifier to the file (module) it is defined in.

We will refer to this as

Types of scope (revisted)

Module interface

The module interface is the list of functions that the module provides (including the documentation)

The interface is separate from the module implementation, which is the code fo the module (i.e., function definitions)

Interface contents

Interface (.h) files

For C modules, the interface is placed in a separate file with a .h file extentsion

clients can read the documentation in the interface to understand how to use the provided functions

The client can also copy and pase the function definitions from the header file

#include

A preprocessor directive temporarily modifies a source file just before it is run (but does not save the modifications)

The directive #include cut and pastes the contents of another file directly into your code

Implementation notes

It is good style to have header files for each module

Referring the reader to interface file is sufficient

// see fun.h for details bool is_fun(int n) { //... }

C standard modules

Unlike Racket, there are no "built-in" functions in C

Fortunately, C provides several standard modules also known as libraries with many useful functions

For example, the stdio module provides printf and scanf

when using #include we use angle brackets <> to specify that the module is one of the standard modules and quotes "" for regular modules (i.e, ones we have written)

#include <stdio.h> #include "mymodule.h"`

13/2/20

cs136.h

#include "cs136.h"

The cs136.h interface file contains:

#include <assert.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h>

Test client

for each module you design, it is good practice to create a test client that ensures the provided functions are correct.

// test-fun.c: testing client for the fun module #include <assert.h> #include "fun.h" int main(void) { assert(is_fun(42)); assert(!is_fun(13)); // ... }

Designing modules

Cohesion and coupling

When designing module interfaces, we want to achieve high cohesion and low coupling

High cohesion means that all the interface functions are related and working toward a "common goal". A module with many unrelated interface functions is poorly designed.

Low coupling means that there is little interaction between modules. It is impossible to completely eliminate module interaction, but it should be minimized.

Interface vs. implementation

Another important aspect of interface design is information hiding, where the interface is designed to hide any implementation details from the client.

Information hiding

The two key advantages of information hiding are

Security

By hiding the implementation details from the client, we gain the flexibility to change the implementation in the future.

Information hiding in C

instead of providing the client with the implementation source code (.c file) you can provide a machine code (e.g., a .ll file).

While C is good at hiding the implementation code, it is not very good at hiding data.

If a malicious client obtains or "guesses" the memory address of some data they can access it directly.

There are disassemblers which are able to "guess" and reverse engineer binary files to potential source code.

Opaque structures in C

Fortunately, C supports opaque structures, which are "good enough" to hide data from a friendly client.

An opaque structure is like a "black box" that the client cannot "see" inside of.

They are implemented in C using incomplete declaration, where a structure is declared without any field.

struct box; // Incomplete Declaration

With an incomplete declaration only pointers to the structure can be defined

struct box my_box; st // Invalid struct box *box_ptr; // Valid

The reason this works is because the fields for the structure are not defined for the client so a non-malicious user cannot change any of the fields.

If a module only provides an incomplete declaration in the interface the the client cannot create an instance of that structure.

Opaque structure example

We will create a small stopwatch module which tracks race times and we do not want clients to be able to tamper with the times

Interface

// stopwatch.h [INTERFACE] struct stopwatch; // stopwatch_create() creates a new stopwatch at time 0:00 // effects: allocates memory (client must call stopwatch_destroy) struct stopwatch *stopwatch_create(void); // stopwatch_destroy(sw) removes memory for sw // effects: sw is no longer valid void stopwatch_destroy(struct stopwatch *sw); // stopwatch_get_seconds(sw) returns the number of seconds in sw int stopwatch_get_seconds(const struct stopwatch *sw); // stopwatch_get_minutes(sw) returns the number of minutes in sw int stopwatch_get_minutes(const struct stopwatch *sw); // stopwatch_add_time(sw, min, sec) adds min[utes] and // sec[onds] to sw // requires: 0 <= minutes, seconds // effects: modifies sw void stopwatch_add_time(struct stopwatch *sw, int min, int sec);

Implementation

// stopwatch.c [IMPLEMENTATION] struct stopwatch { int min; int sec; }; // requires: 0 <= min // 0 <= sec <= 59 int stopwatch_get_seconds(const struct stopwatch *sw) { assert(sw); return sw->sec; } int stopwatch_get_minutes(const struct stopwatch *sw) { assert(sw); return sw->min; } // stopwatch.c [IMPLEMENTATION] void stopwatch_add_time(struct stopwatch *sw, int min, int sec) { assert(sw); assert(sec >= 0); assert(min >= 0); sw->min += min; sw->sec += sec; while (sw->sec >= 60) { sw->min += 1; sw->sec -= 60; } }

Example client

// client.c #include "cs136.h" #include "stopwatch.h" int main(void) { struct stopwatch *sw = stopwatch_create(); stopwatch_add_time(sw, 1, 59); stopwatch_add_time(sw, 3, 30); trace_int(stopwatch_get_minutes(sw)); trace_int(stopwatch_get_seconds(sw)); stopwatch_destroy(sw); }

Maintainability

We can improve our stopwatch module without changing the client. This is an example of maintainability

// stopwatch.c [IMPLEMENTATION] static const int seconds_per_minute = 60; void stopwatch_add_time(struct stopwatch *sw, int min, int sec) { assert(sw); assert(sec >= 0); assert(min >= 0); const int total_time = (min + sw->min) * seconds_per_minute + sec + sw->sec; sw->min = total_time / seconds_per_minute; sw->sec = total_time % seconds_per_minute; }

Flexibility

Because we have used information hiding to design our interface, our implementation is not only maintainable but also flexible

We can change the design of our struct stopwatch and the client will be completely unaware

Data structures & abstract data types

In the previous stopwatch example, we demonstrated two implementation with different data structures:

For each data structure we knew how the data was "structured"

However, the client doesn't need to know how the data is structured. The client only requires an abstract understanding that a stopwatch stores time information.

The stopwatch module is an implementation of a stopwatch Abstract Data Type (ADT)

Formally, an ADT is mathematical model for storing and accessing data through operations. As mathematical models they transcend any specific computer language or implementation.

In practice ADTs are implemented as data storage modules that only allow access to the data through interface functions (ADT operations). THe underlying data structure and implementation of an ADT are hidden from the client (which provides flexibility and security).

25/2/20

Arrays

C only has two built-in types of "compound" data storage:

int my_array[6] = {1, 2, 3, 4, 5, 6};

To define an array we must know the length of the array in advance (we address this limitation in Section 10).

Each individual value in the array is known as an element. To access an element, its index is required

Array initialization

Arrays can only be initialized with braces ({})

int a[6] = {1, 2, 3, 4, 5, 6}; a = {0, 0, 0, 0, 0, 0} // INVALID a = ??? ; // INVALID

Once defined the entire array cannot be mutated at once. Only individual elements can be mutated.

If there are not enough elements in the initialization braces, the remaining values are initialized to zero.

int b[5] = {1, 2, 3}; // b[3] & b[4] = 0

character arrays can be initialized with double quotes (") for convenience.

The following two definitions are equivalent:

char a[3] = {'c','a','t'}; char b[3] = "cat";

Like variables, the value of an uninitialized array depends on the scope of the array:

Array length

C does not explicitly keep track of the array length as part of thiearray data structure

To improve readability, the array length is often stored in a separate variable. `

int a[6] = {1, 2, 3, 4, 5, 6}; const int a_len = 6;

It might seem better to use a constant to specify the length of an array.

const int a_len = 6; int a[a_len] = {1, 2, 3, 4, 5, 6}; // NOT IN CS136

This would appeare to be a "better style"

However the syntax to do this properly is outside the scope of this course.

A preferred syntax to specify the length of an array is to define a macro.

#define A_LEN 6 int main(void) { int a[A_LEN] = {1, 2, 4, 5, 6}; //... }

Theoretically, in some circumstances sizeof can be used to determine the length of an array.

int len = sizeof(a) / sizeof(a[0]);

Array size

The length of an array is the number of elements in the array

The size of an array is the number of bytes it occupies in memory

An array of kk elements, each of size s, requires exactly k⋅sk \cdot s bytes.

In the C memory mode, array elements are adjacent to each other. Each element of an array is placed in memory immediately after the previous element.

The array identifier

The value of an array (a) is the same as the address of the array (&a), which is also the address of the first element (&a[0]).

int a[6] == {4, 8, 15, 16, 23, 42}; trace_ptr(a); // a => 0x5000 trace_ptr(&a); // &a => 0x5000 trace_ptr(&a[0]); // &a[0] => 0x500

Passing arrays to functions

When an array is passed to a function, only the address of the array is copied into the stack frame.

This is more efficient than copying the entire array to the stack.

Typically, the length of an array is unknown to the function, and is a separate parameter

There is no method for "enforcing" that the length passed to a function is valid

Functions should require that the length is valid, but there is no way for a function to assert that requirement.

As we have seen before, passing an address to a function allows the function to mutate the contents tat hat address.

int sum_array(int a[], int len) { int sum = 0; for (int i = 0; i < len; ++i) { sum += a[i]; } return sum; } int main(void) { int my_array[6] = {4, 8, 15, 16, 23, 42}; trace_int(sum_array(my_array, 6)); }
void array_negate(int a[], int len) { for (int i = 0; i < len; ++i) { a[i] = -a[i]; } }

It's good style to use the const keyword to both prevent mutation and communicate that no mutations occurs. `

int sum_array(const int a[], int len) { int sum = 0; for (int i = 0; i < len; ++i) { sum += a[i]; } return sum; }

Pointer arithmetic

We have not yet discussed any pointer arithmetic

C allows an integer to be added to a pointer, but the result may not be what you expect.

If p is a pointer, the value of (p+1) depends on the type of the pointer p.

(p+1) adds the sizeof whatever p points at.

27/2/20

When adding an integer i to a pointer p, the address computed by (p + i) in C is given in normal arithmetic by :

p+i⋅sizeof(∗p)p + i \cdot sizeof(*p)

Subtracting an integer from a pointer (p- i) works in the same way.

Mutable pointers can be incremented (or decremented). ++p is equivalent to p = p + 1;

you cannot add two pointers

A pointer q can be subtracted from another pointer p if the pointers are the same type (point to the same type). The value of (p-q) in C is given in normal arithmetic by:

p−qsizeof(∗p)\frac{p-q}{sizeof(*p)}

In other words, if p = q + i then i = p - q

Pointers (of the same type) can be compared with the comparison operators: <, <=, ==, !=, =>, >

Pointer arithmetic and arrays

Pointer arithmetic is useful when working with arrays

The array indexing syntax ([]) is an operator that performs pointer arithmetic. a[i] is equivalent to *(a+i)

Pointer arithmetic and arrays

Pointer arithmetic is useful when working with arrays

The array indexing syntax ([]) is an operator that performs pointer arithmetic. a[i] is equivalent to *(a+i)

C does not perform any array "bounds checking". For a given array a of length ll, C does not verify that a[j] is valid (0≤j<l0 \leq j < l), C simply translates a[j] to *(a+j), which may be outside the bounds of the array (e.g, a[100000000] or a[-1]) This is a common source of errors and bugs and a common criticism of C. Many modern languages have fixed this shortcoming and have "bounds checking" on arrays

int array[5] = {0, 1, 3, 4}; for (int i = 0; i < 5; i++) { printf("%d ", i[array]); } // output: 0 1 2 3 4
int sum_array(const int *a, int len) { int sum = 0; for (const int *p = a; p < a + len; ++p) { sum += *p; } return sum; } int sum_array(const int a[], int len) { int sum = 0; for (int i = 0; i < len; ++i) { sum += a[i]; } return sum; }
const int *p; int const* p; int * const p; const int const *p;

Array map

Aside from the awkward function pointer parameter syntax, the implementation of array_map is straightforward

// array_map(f, a, len) replaces each element a[i] // with f(a[i]) // effects: modifies a void array_map(int (*f)(int), int a[], int len) { for (int i = 0; i < len; ++i) { a[i] = f(a[i]); } }
#include "array_map.h" int add1(int i) { return i + 1; } int sqr(int i) { return i * i; } int main(void) { int a[6] = {4, 8, 15, 16, 23, 42}; print_array(a, 6); array_map(add1, a, 6); print_array(a, 6); array_map(sqr, a, 6); print_array(a, 6); } // 4, 8, 15, 16, 23, 42. // 5, 9, 16, 17, 24, 43. // 25, 81, 256, 289, 576, 1849.

Selection sort

void selection_sort(int a[], int len) { int pos = 0; for (int i = 0; i < len - 1; ++i) { pos = i; for (int j = i + 1; j < len; ++j) { if (a[j] < a[pos]) { pos = j; } } swap(&a[i], &a[pos]); // see Section 05 } } // Notes: // i: loops from 0 ... len-2 and represents the // "next" element to be replaced // j: loops from i+1 ... len-1 and is "searching" // for the next smallest element // pos: position of the "next smallest"

Insertion sort

In insertion sort, we consider the first element to be a sorted sequence (of length one)

We then "insert" the second element into the existing sequence into the correct position. and then the third element, and so on.

For each iteration of Insertion sort, the first i elements are sorted. We then “insert” the element a[i]into the correct position, moving all of the elements greater than a[i] one to the right to “make room” for a[i].

void insertion_sort(int a[], int len) { for (int i = 1; i < len; ++i) { for (int j = i; j > 0 && a[j - 1] > a[j]; --j) { swap(&a[j], &a[j - 1]); } } }

Quicksort

Quick ort is an example of a "divide & conquer" algorithm.

First, an element is selected as a "pivot" element.

The list is then partitioned (divided) into two sub-groups: Less than (or equal to) the pivot and those greater than the pivot.

Finally, each subgroup is then sorted

Quick sort in racket:

(define (quick-sort lon) (cond [(empty? lon) empty] [else (define pivot (first lon)) (define less (filter (lambda (x) (<= x pivot)) (rest lon))) (define greater (filter (lambda (x) (> x pivot)) (rest lon))) (append (quick-sort less) (list pivot) (quick-sort greater))]))

30/1/20