cs31 lecture 8

X c allows at most one item to be returned how to

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: be returned. How to model C++ algorithms with multiple outputs? algorithms x Data movement is costly x Sometimes, the data is not fully known in advance 8 Content vs. Address of a memory slot x Central concept: the value in a memory cell can be: An actual 32-bit number The address of another memory cell x Intuition: M = [ 2 | 3 | 0x9 | 2 | 3 ] 0x9 01 2 34 M[0] contains 2 The value at address 0 is 2 M = [ 2 | 3 | 0x9 | 2 | 3 | 0x0 ] 0x9 01 2 34 5 M[5] contains the address of slot 0 9 Address of a memory slot x M[5] contains the address of the slot 0 x To get the value of slot 5, do M[5] (it is an address) x To get the value in slot 0, do M[M[5]] (it is a value) x To get the address of M[5], do 5 (often noted 0x5) x These are the concepts of pointers and addresses! x The compiler knows the difference between M[5] and The M[M[5]] based on the types of the variables M[M[5]] 10 Pass-by-reference x Central idea: instead of copying the value of the argument, Central simply copy the address where the arguments are stored simply x Major differences with pass-by-value Modifying the value of the arguments inside the function changes Modifying their value at the call site their Whatever the type of data, only 32 bits (or 64 bits) are copied x In C++, append the & symbol to the type of the argument to In mark an argument as passed-by-reference mark x Be careful: some types are pass-by-reference by default Be (i.e., arrays) (i.e., 11 The example revisited int foo(int& a, int& b) { int c = a + b; int return c; return } int main() { int tmp_a = 2; int tmp_b = 3; int return foo(tmp_a, tmp_b); return } x Memory at the beginning of the function call: M = [ 2 | 3 | 0x9 | 0x0 | 0x1 ] 0x9 01 2 3 4 M[3] is the first argument, M[M[3]] is its value 12 Observations M = [ 2 | 3 | 0x9 | 0x0 | 0x1 ] 0x9 01 2 3 4 x In C++, for this example, the variable int& a is linked to In M[3] M[3] x When assigning/reading a, the compiler automatically When implemented M[M[3]] implemented Ex: a = a + 1; // translates into M[M[3]] = M[M[3]] + 1; x In the pass-by-value case, for int a, the compiler In automatically implements M[3] automatically Ex: a = a + 1; // translates into M[3] = M[3] + 1; 13 More observations x In general, there can be an unlimited number of references In to the same memory slot: to M = [ 2 | 3 | 0x9 | 0x0 | 0x0 | 0x0 | 0x0 ] 0x9 01 2 3 4 5 6 Example in C++: void foo(int& a, int& b, int& c) { } int main() { int bar = 42; int foo(bar, bar, bar); foo(bar, } 14 Mor...
View Full Document

This note was uploaded on 04/03/2014 for the course CS 31 taught by Professor Melkanoff during the Fall '00 term at UCLA.

Ask a homework question - tutors are online