Handouts to accompany "A C++ Crash Course: Part I"

Discussion Point I: Procedural vs Object-Oriented Progamming

Give an example of a program that can be written in an object-oriented manner:





Give an example of a program that can be written in a procedural manner:





Exercise I: Functions and Memory Layout

Given the following:
void aFunc( int x, int y ) {
    double d1 = x + y;
}
int main( int argc,
          const char * argv[] ) {
    int x = 7;
    aFunc( 1, 2 );
    aFunc( 2, 3 );
    return 0;
}
Draw what the stack looks like after the first and second calls to aFunc. What does the stack look like after main() has executed?

Exercise II: Arrays

What will the following program print out? Explain why.
void penguin( int array[], int i )
{
    a[ 3 ] = 21;
    i = 21;
}

int main( int argc, const char * argv[] )
{
    int a[ 5 ];
    a[ 0 ] = 0;
    a[ 1 ] = 1;
    a[ 2 ] = 2;
    a[ 3 ] = 3;
    a[ 4 ] = 4;

    int b = -1;

    penguin( a, b );

    print a;  // PSEUDOCODE: prints array elements in order
    print b;  // PSEUDOCODE: prints the value of b

    return 0;
}






Why are arrays not passed by copy? (Hint: the size of a stack frame is computed long before the program is run [specifically, at compile time])



Exercise III: Pointers

Consider the following program:
int penguin( int * px, int * py, int z );
int duck( int * px, int * py );

int main( int argc, const char * argv[] )
{
    int a = 3;
    int b = 21;
    int c = 76;

    b = penguin( &a, &b, c );

    print "b is ", b;  // PSEUDOCODE

    return 0;
}

int penguin( int * px, int * py, int z )
{
    int w = *py + 10;
    duck( px, &z );
    duck( py, px );
    duck( &w, &z );

    return *px + q;
}

int duck( int * px, int * py )
{
    int v = *px - 1;
    *px = *py;
    *py = v;

    print "v is ", v;  // PSEUDOCODE again
}
The value of v will be printed three times. Show the state of memory at each of these times. You may use either a memory-layout or a box-and-arrows diagram.











What does the program print out as the value of b?