CS 136 - Week 3
Class 5 - January 20, 2025
- Always write for clarity
- Do one thing at once
- It is good to use
constwhen appropriate
Side effects
- YOU ARE REQUIRED to document a function's side effects
- Mutation: changing the contents of memory
- I/O: Input and Output (interacting with things outside the program)
- Something can be mutation but not a side effect. If it doesn't change anything outside the program but just mutates a variable, it is not a side effect but is mutation.
- the
printffunction produces a side effect.- Write
// effects: produces outputin any function documentation with theprintffunction
- Write
Testing
- create
<stem>.inthat will be used as "input" for the program - create
<stem>.expectthat will be used as the expected "output" for the program - Always add a new line at the end of each file
trace_<blank>goes to stderror stream- When you include
trace_int(n)for example, it's NOT a side effect as it goes to the stderror stream not stdout
Reading input
- We write code like this:
int x = 0;
int retval = scanf("%d", &x)
- The
"%d"tells it to read a decimal integer - Two things happen:
scanfreturns an int indicating how many values it read- Don't omit the
&
- DO NOT check for
-1when usingscanf. It will be different for different libraries. You check for the number of matched items. - Use this:
// Add files to test this program.
// Do not modify main.c in any way.
#include "cs136.h"
int main(void) {
int val = 0;
int retval = 0;
retval = scanf("%d", &val);
if (1 == retval) {
printf("Read an int: %d\n", val);
} else {
printf("Failed to read: val is still %d\n", val);
printf("retval is %d\n", retval);
}
}
This is a stream of input:
2 4 6 0 1
scanf reads one character at a time. There's no way for it to go back. After it's read one thing, the paper is essentially shredded. Think of the long stream of tape
WHAT THE HELL IS GOING ON HERE
Class 6 - January 22, 2025
- Forget about substitution rules for Racket
- In C, if you think about modeling C this way, it won't work!
- To trace a C program, imagine it by going line by line
- Build intuition, but don't try to memorize "rules" for how it works
- We already know:
- Starts in main function
- Control flow jumps when a function is called