CS 208 s21 — Learning Block #8
Table of Contents
1 Review
- Before we dive in, a quick review of some C concepts1
void swap(long* xp, long* yp) { long t0 = *xp; long t1 = *yp; *xp = t1; *yp = t0; }
- what type of data are these parameters, what size?
- what is the effect of this function?
- How would we call?
long a = 10; long b = 42; swap(???);
2 swap example
- see the slides here: swap-slides.pdf
- what happens when you only use one temporary variable in the C implementation of
swap?- i.e.,
*xp = *ypinstead of lines 2 and 3
- i.e.,
3 Practice
- CSPP practice problems 3.1 (p. 182) and 3.5 (p. 189)
- Write C code for
mystery()2
void mystery(long* xp, long* yp, long *zp) // xp in %rdi, yp in %rsi, zp in %rdx
mystery: movq (%rdi), %r8 movq (%rsi), %rcx movq (%rdx), %rax movq %r8, (%rsi) movq %rcx, (%rdx) movq %rax, (%rdi) ret
Footnotes:
1
- what type of data are these parameters, what size?
xpandypare pointers to long. As pointers, they each take 8 bytes. - what is the effect of this function?
swapswitches the values thatxpandyppoint to. They still point to the same locations in memory, but the values at those locations have been switched. - How would we call
swap? Use the&operator to get the address ofaandb. After the call toswap,awould be 42 andbwould be 10.
long a = 10; long b = 42; swap(&a, &b);
2
There are many different C implementations of mystery that would be consistent with the given assembly, here is one possibility:
void mystery(long *xp, long *yp, long *zp) { long t0 = *xp; long t1 = *yp; long t2 = *zp; *yp = t0; *zp = t1; *xp = t2; }