cs31 lecture 17

Of i local to the function 42 j 43 j just refers 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: gion 1 ends. / } // region 1 ends 77 The case of for loops x The <init> clause of the for loop belongs to the scope of The the for loop the x Be careful: a for loop is a nested scope: for (int i = 42; i < 100; ++i)
 sum += i; sum Is translated into: { // scope 1 starts int i = 42; int while (i < 100)
 { /// scope 1.1 starts / sum += i; sum ++i; ++i; } 78 Typical problems x Re-defining a variable that was previously defined (not an Re-defining error: it is a valid C++ behavior)
 error: x Trying to use a variable not defined in the current scope x Defining a missing variable in the wrong scope 79 A word on program arguments x Early intuition: the arguments of a function are stored on Early the stack the x Their value can be stored, or only a “pointer” to where the Their value is value pass-by-value pass-by-reference x In C++, scalar types (bool, int, float, double, char, …)
 are In passed by value: an actual copy is made passed x They can be passed by reference, using They <type1>& arg <type1>& 80 Examples void foo(int i, int& j)
 { i = 42; // there is a copy of i, local to the function 42; j = 43; // j just refers to an address in memory, outside the function 43; } int main()
 { int p = 1, q = 2; int foo(p, q)
; foo(p, std::cout << “p: “ << p << “ q: “ << q << std::endl; // prints p: 1 q: 43 std::cout return 0; return } 81 A word on strings in C++ x A string is a vector of charact...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online