1 of 71

C++ Functions

Pointers & References

C. Papachristos

Robotic Workers Lab

University of Nevada, Reno

CS-202

2 of 71

Monday

Tuesday

Wednesday

Thursday

Friday

 

 

 

Lab (8 Sections)

 

 

CLASS

 

CLASS

 

PASS Session�(Tentative)

PASS Session�(Tentative)

Project DEADLINE

NEW Project

 

Course Week

CS-202 C. Papachristos

Course , Projects , Labs:

Your 1st Project Deadline is this Wednesday 1/29.

  • PASS Sessions TBD, once established use them to get all the help you need!

  • 24-hrs delay after Project Deadline incurs 20% grade penalty.
  • Past that, NO Project accepted. Better send what you have in time!

3 of 71

Today’s Topics

CS-202 C. Papachristos

C++ Functions

  • Parts

Prototype

Definition

Call

  • Return
  • Parameters / Arguments
  • Libraries

Pointers

References

4 of 71

Functions

CS-202 C. Papachristos

Function Parts

Function Declaration (Prototype)

  • Information for compiler to properly interpret calls.

Function Definition (Implementation)

  • Actual implementation (i.e., code) for function.

Function Call

  • How function is actually used by program.
  • Transfers execution control to the function.

5 of 71

Functions

CS-202 C. Papachristos

Function Declaration (Prototype)

Gives compiler information about the function

  • How to interpret calls to the function.

<return type> <function_name> (<parameter_types>);

double sprintSum (int, double, char []);

double sprintSum (int n, double d, char s[]);

Must list the parameters’ data types (at least).

Placed before any calls

In declaration space of main().

Or above main() for global access.

Forward Declaration :

Semicolon-terminated

or

6 of 71

Functions

CS-202 C. Papachristos

Function Definition (Implementation)

Definition of the function:

double sprintSum (int n, double d, char s[]) {

double sum = d + n;

sprintf(s, "%.3f", sum);

return sum;

}

  • Function definition must match prototype.

Placed AFTER the function main() (NOT inside).

  • All definitions of equal order, no function needs to be contained inside another.

  • Function name, parameter(s) type, and return type all must match the prototype’s.
  • return statement sends data back to the caller.

Function Block :

Brace-enclosed

7 of 71

Functions

CS-202 C. Papachristos

Function Call

Much like a standard C call:

char printSum[256];

double returnSum = sprintSum(10, 0.1, printSum);

  • Returns a double.

(Assigned to variable returnSum)

Arguments:

  • The literals 10, 0.01.

(Can also pass variables – do they have to be int and double?)

  • A char array variable printSum

(Has to match char [] type – formally char *.)

8 of 71

#include <iostream>

using namespace std;

double desiredVelocity(double distance, double time, int max_velocity);

int main()

{

double distance, time;

cout << "How far will you travel (in km)?\n";

cin >> distance;

cout << "In how much time should you get there (in hrs)?\n";

cin >> time;

double velocity = desiredVelocity(distance, time, 200);

cout << "You should travel at a speed of: " << velocity << "[km/h]";

return 0;

}

double desiredVelocity(double distance, double time, int max_velocity)

{

double velocity = distance / time;

velocity = (velocity > max_velocity) ? max_velocity : velocity;

velocity = (velocity < -max_velocity) ? -max_velocity : velocity;

return velocity;

}

Functions

CS-202 C. Papachristos

Function Parts

  • Function Prototype

  • Function Definition

  • Function Call

9 of 71

Functions

CS-202 C. Papachristos

return Statement(s)

Transfers control back to the calling function.

Special case: “void” functions:

No value back, Functions that only have side effects (e.g., print out information).

Similar declaration to “regular” functions

void printResults(double cost, double tax);

Optional return statement (all other return types must have a return statement).

Typically the last statement in the definition.

Can also have multiple return statements.

  • Transfers control early, (anything past it in the function Block is not executed).
  • Can have multiple exit points in a function.

Typical use: guard statements ( if(somethingWrong) return; ).

10 of 71

Functions

CS-202 C. Papachristos

Function Parameters / Arguments

(Function) Parameter:

  • Formal variable, as it appears in the function prototype.
  • Part of the Function Signature (more on that later).

(Function) Argument:

  • Actual value or variable.
  • An expression used when making the function call.

Multiple Parameters / Arguments:

double precisionSum(double a, double b);

cout << precisionSum(0.1 * 1000000, 1e-3);

100.001

11 of 71

Functions

CS-202 C. Papachristos

Function Parameters / Arguments

Variadic Functions & Arguments :

double precisionMultiSum(int numargs, ...);

#include <iostream>

#include <cstdarg>

double precisionMultiSum(int numargs, ...){

double sum = 0;

va_list ap;

va_start(ap, numargs);

for (int i=0; i<numargs; ++i)

sum += va_arg(ap, double);

va_end(ap);

return sum;

}

int main() {

std::cout << precisionMultiSum(2, 5.0, 2.0);

return 0;

}

Actually

Preprocessor Macros

are used to reinterpret

parameter: ...

in expressions where precisionMultiSum appears.

What if ?

precisionMultiSum(2, 5, 2);

precisionMultiSum(2, 5.0, 2);

precisionMultiSum(2, 5, 2.0);

Example Calls:

precisionMultiSum(2, 1.0, 2.0);

precisionMultiSum(3, 0.1, 0.2, 0.3);

12 of 71

Functions

CS-202 C. Papachristos

Function Pre / Post - Conditions

Include function headers with intuitive documentation in your code.

  • Contain name, pre / post – conditions:

Pre/Post-Conditions include assumptions about program state, not just the input and output.

/** Displays the interest for a given balance and rate

* @param balance The balance value

* @param rate The interest rate

* @pre The balance is non-negative account balance,

* and the rate is interest rate as percentage

* @post Prints on terminal the amount of interest

* @return The amount of interest given the balance,

* at the given rate

*/

double showInterest(double balance, double rate);

Note:

Simple Code Comments:

// Single-line Comment Here

or

/* Multi-line

Comments Here */

Pre-�Condition:

Post-�Condition:

Description:

13 of 71

Functions

CS-202 C. Papachristos

C++ Function Libraries

Full of useful functions!

Must “#include” appropriate library.

  • Correspondence to “C” libraries:

<cmath> ~ <math.h>

<cstdlib> ~ <stdlib.h>

<cstring> ~ <string.h>

  • Console-File I/O:

(e.g. std::cout, std::cin)

<iostream>

  • Many more…

C++

C analog

Table from:

Absolute C++

Copyright © 2016

Pearson, Inc.

All rights reserved.

14 of 71

Functions

CS-202 C. Papachristos

The main() Function

“Special” function, serves as entry point to the program.

Only one main() can exist in a program.

Called by the Operating System, not by the programmer!

Should return an integer (0 is traditional, Clean-termination/No-error return code).

Function Functionalities

  • Build “blocks” of programs
  • Divide and conquer large problems

Note:

Functions in C++ can only return one thing!

(one type of variable)

  • Increases readability and reusability
  • Separate source files from main() for easy sharing.
  • This might seem limited, for now…

15 of 71

Functions

CS-202 C. Papachristos

Functions & Parameters

Methods of passing arguments to functions:

  • Pass-by-Value:

A “Copy” of the value of the actual argument is used.

  • Pass-by-Reference:

The “Actual” argument itself is used.

  • Pass-by-Address:

A “Copy” of the value of the argument is used …

(but:) the argument is a special type that allows to in-directly use another variable.

16 of 71

Functions – Pass-by-Value

CS-202 C. Papachristos

Pass-by-Value

A simple function that adds 1 to an integer and returns the new value:

Declaration:

int addOne (int num) {

return ++num;

}

When the addOne() is called, the value of the variable is passed in as an argument.

The value is saved in addOne()’s local variable num.

  • Remember Variable Scope!

Changes made to local variables do not affect anything outside of Scope Block.

The main() and addOne() can’t see each other’s variables.

Call:

int enrolled = 99;

addOne(enrolled);

enrolled: 99

17 of 71

Functions – Pass-by-Value

CS-202 C. Papachristos

Pass-by-Value

A simple function that adds 1 to an integer and returns the new value:

Declaration:

int addOne (int num) {

return ++num;

}

Copy of actual argument passed.

  • Considered “local variable” inside function.
  • If modified, only “local copy” changes.

Function has no access to Actual argument from caller.

  • This is the “default” method.

Call:

int enrolled = 99;

addOne(enrolled);

enrolled = addOne(enrolled);

enrolled: 99

enrolled: 100

18 of 71

Functions – Pass-by-Value

CS-202 C. Papachristos

Pass-by-Value

A common mistake:

  • Declaring parameter “again” inside the function:

double fee(int hoursWorked, int minutesWorked)

{� int quarterHours; � int minutesWorked � }

Compiler error: "error: declaration of 'int minutesWorked' shadows a parameter…"

  • Parameters are like local variables.
  • Function will “declare and create them” automatically.

Local Variable

Shadowing

19 of 71

References

CS-202 C. Papachristos

Reference-Types

Reference-Type variable declaration with the ampersand (&) symbol.

int x = 10;

int & xRef = x;

Once created, they don’t need the ampersand (&) or asterisk (*) in their use.

  • They are actually “Aliases” to pre-existing variables.

Rules:

  • References must be initialized at declaration (they have to Alias something).

Once initialized, they are forever tied to the thing they reference.

No such thing as a NULL reference (unlike a NULL pointer).

  • References cannot be changed (any attempt to assign just references the aliased variable).
  • References are another “name” for a variable (dereferencing does not make sense).

(They look like normal variables)

20 of 71

References

CS-202 C. Papachristos

Reference-Types

Reference-Type variable declaration with the ampersand (&) symbol.

int x = 10;

int & xRef = x;

Once created, they don’t need the ampersand (&) or asterisk (*) in their use.

  • They are actually “Aliases” to pre-existing variables.

Rules:

  • From the C++11 standard:

[dcl.ref] [...] a NULL reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a NULL pointer, which causes undefined behavior.

(They look like normal variables)

21 of 71

Functions – Pass-by-Reference

CS-202 C. Papachristos

Pass-by-Reference ( & )

Provides access to caller’s Actual argument.

  • Caller’s data can be modified by called function!

Typically used for input function.

  • To retrieve data for caller.

Specified by ampersand (&) after type in formal parameter list (Function Definition).

<return type> <function_name> (<parameter type> & );

void squareThisNumber (int & n);

vs

int squareNumber (int n);

by-Value: Copy-of Argument

by-Reference: Actual Argument

22 of 71

Functions – Pass-by-Reference

CS-202 C. Papachristos

Pass-by-Reference ( & )

What is really passed in:

  • Reference to something that exists outside of the function scope.

The “Actual” argument (vs its “Copy”).

Example (with contrast to Pass-by-Value model) :

Declaration:

void addOne (int & num) {

++num;

return;

}

Call:

int enrolled = 99;

addOne(enrolled);

enrolled: 100

23 of 71

Functions – Pass-by-Reference

CS-202 C. Papachristos

Pass-by-Reference ( & )

No need to return anything!

#include <iostream>

using namespace std;

/** Reads values for 2 ints using the console

*/

void getInts(int & val1, int & val2);

/** Swaps the values of 2 ints

*/

void swapInts(int & val1, int & val2);

/** Prints the values of 2 ints to console

*/

void printInts(int val1, int val2);

int main()

{

int a, b;

getInts(a, b);

swapInts(a, b);

printInts(a, b);

return 0;

}

void getInts(int & val1, int & val2)

{

cout << "Enter 1-st int: ";

cin >> val1;

cout << "Enter 2-nd int: ";

cin >> val2;

}

void swapInts(int & val1, int & val2)

{

int temp = val1;

val1 = val2;

val2 = temp;

}

void printInts(int val1, int val2)

{

cout << "1-st int: " << val1 <<

"2-nd int: " << val2 << endl;

}

24 of 71

Functions – Pass-by-Reference

CS-202 C. Papachristos

Reference Caveats

Reference-Type variable declaration with the ampersand (&) symbol.

int & xRef = x;

  • Essentially Pass-by-Reference is achieved by passing Reference-Type parameters.
  • Using them looks identical to using a value (Is easier always a good thing?)

May easily think you’re passing by value…

void changeByRef (int x){

x = x + 1;

cout << "changeByRef " << x << "\n";

}

Output: changeByRef 2

main 1

int x = 1;

changeByRef( x );

cout << "main " << x << "\n";

25 of 71

Functions – Pass-by-Reference

CS-202 C. Papachristos

Reference Caveats

Reference declaration the ampersand (&) symbol.

int & xRef = x;

  • Essentially Pass-by-Reference is achieved by declaring Reference-type parameters.
  • Using them looks identical to using a value (Is easier always a good thing?)

May easily think you’re passing by value…

void changeByRef (int & x){

x = x + 1;

cout << "changeByRef " << x << "\n";

}

Output: changeByRef 2

main 2

int x = 1;

changeByRef( x );

cout << "main " << x << "\n";

26 of 71

Functions – Pass-by-Reference

CS-202 C. Papachristos

const-Reference Parameters (const &)

Calling-by-Reference arguments is inherently “dangerous”:

  • Caller’s data can be changed, sometimes NOT desirable behaviour.

Common technique to “protect” data:

The keyword const.

void sendConstRef(const int & par1, const int & par2);

  • No changes allowed inside function body, arguments have “read-only” qualification.

Note: const-Reference yields different Function Signature than non-const Reference…

These are 2 separate functions and

each can be used to do a different

thing (separate implementions).

meters.feet(const double & ft);

meters.feet(double & ft);

27 of 71

main()

Pointers

CS-202 C. Papachristos

Addresses

Remember the Pass-by-Value model :

int age = 18;

age = addOne( age );

0x1015

18

age

int addOne ( int num ) {

return ++num;

}

Function Scope

This is the variable Address:�Addresses commonly represented�by HEX numbers

Where it “lives” in the program memory, the starting memory location

28 of 71

main()

Pointers

CS-202 C. Papachristos

Addresses

Remember the Pass-by-Value model :

int age = 18;

age = addOne( age );

0x1015

18

age

int addOne ( int num ) {

return ++num;

}

Function Scope

This is the variable Value:�Its value semantics are determined by its type.�It is a representation of the memory content (sequence of bytes) starting at its Address and with a total number defined by the type.

29 of 71

main()

addOne()

Pointers

CS-202 C. Papachristos

Addresses

Remember the Pass-by-Value model :

int age = 18;

age = addOne( age );

0x1015

18

age

int addOne ( int num ) {

return ++num;

}

0x5286

18

Function Scope

Function Scope

Addresses commonly

HEX numbers

num

30 of 71

main()

addOne()

Pointers

CS-202 C. Papachristos

Addresses

Update via return value and assignment:

int age = 18;

age = addOne( age );

0x1015

19

age

int addOne ( int num ) {

return ++num;

}

0x5286

19

Function Scope

Function Scope

num

age, num

in separate Scopes.

31 of 71

main()

Pointers

CS-202 C. Papachristos

Addresses

After Function Call:

int age = 18;

age = addOne( age );

0x1015

19

age

int addOne ( int num ) {

return ++num;

}

Function Scope

num not reachable outside this Block Scope

(would not be available even if it were a static variable, it is not a life-time issue)

32 of 71

int

Pointers

CS-202 C. Papachristos

Addresses-of Operator ( & )

To get the Address-Of a variable we pre-pend the ampersand (&) operator to its name.

int age = 18;

0x1015

18

age

cout << age; Output: 18

cout << &age; Output: 0x1015

33 of 71

Pointers

CS-202 C. Papachristos

Pointer

A Variable whose Value holds the Address-Of something somewhere in memory.

int x = 37;

int * ptr = (int *)0x7ffedcaba5c4;

cout << "x is " << x << endl;

cout << "ptr is " << ptr << endl;

This will print out something like:

x is 37

ptr is 0x7ffedcaba5c4

Addresses commonly

HEX numbers

Typecasting a long number to an int * value here to set a specific HEX value to the pointer.

(This is just for demonstration in this context�and is never done in practice, because otherwise the value of the pointer variable would be left uninitialized !)

34 of 71

Pointers

CS-202 C. Papachristos

Pointer Utility

Pointers are incredibly useful in programming.

  • Allow functions to:

Modify multiple arguments.

Use and modify arrays as arguments.

  • Increase program (compiled function) efficiency.

  • Creation / handling / use of Dynamic Objects (more on that later).

35 of 71

Pointers

CS-202 C. Papachristos

Pointer Declaration

A pointer is just like any regular variable. It has:

  • Type
  • Name
  • Value (what kind?)

Pointer declaration /creation requires the (*) symbol.

int x = 37;

int * ptr = NULL;

cout << "x is " << x << endl << "ptr is " << ptr << endl;

Note: Typical pointer initialization to value NULL ensures that�we don’t end up with a random uninitialized value !

36 of 71

Pointers

CS-202 C. Papachristos

Pointer Declaration

Valid pointers declaration / creation statements:

int *ptr1;

int* ptr2;

int * ptr3;

int*ptr4;

Note:

  • Multiple pointers inline declaration / creation:

int * ptr1, * ptr2, * ptr3;

int * ptr1, ptr2, ptr3;

Just avoid the last one.

Looks right, but no,� this declares an int * and 2 ints

37 of 71

int

Pointers

CS-202 C. Papachristos

Pointer Value

As earlier stated, pointers are “Just Variables”.

  • Pointer’s Value: an Address in memory (instead of storing an int/float/char/etc.)

Note: Pointer’s size in memory is not guaranteed (implementation-defined).

int *

0x1015

18

0x5286

0x5025

ptr

num

Addresses

Values

Where it “lives” in memory.

Where it points-to

in memory

38 of 71

Pointers

CS-202 C. Papachristos

Pointer Assignment

Value (pointed-to Address) assignment:

  • To get the Address-Of a variable we use the ampersand (&) operator.

int x = 5;

int * xPtr = NULL;

xPtr = &x;

  • Pointer-to-pointer assignment (also valid):

int * yPtr;

yPtr = xPtr;

Simple grammar:

“Pointer-value gets assigned the Address-of variable x”.

39 of 71

Pointers

CS-202 C. Papachristos

Pointer Assignment

Value (pointed-to Address) assignment:

Address-Of a Value is not enough for a valid assignment!

  • Pointer has a Type.

int x = 5;

char * ptr5 = &x ;

Pointer type must match the type of the variable whose address it stores.

Compiler error: error: cannot convert ‘int*’ to ‘char*’ in initialization.”

40 of 71

int

Pointers

CS-202 C. Papachristos

Pointer Assignment

Assignment means telling the pointer what memory address to point to:

int num = 18;

int * ptr = &num;

int *

18

0x5286

0x1015

ptr

num

Addresses

Values

Where it “lives” in memory.

Where it points-to

in memory

0x1015

41 of 71

Pointers

CS-202 C. Papachristos

Indirection (Dereference) Operator ( * ) or “Value-Pointed-By”

To refer to the Value-Pointed-By a pointer, we pre-pend the star (*) operator to its name.

… = *ptr

*ptr = …;

int

int *

18

0x5286

0x1015

ptr

num

Addresses

Values

0x1015

42 of 71

Pointers

CS-202 C. Papachristos

Indirection (Dereference) Operator ( * ) or “Value-Pointed-By”

To refer to the Value-Pointed-By a pointer, we pre-pend the star (*) operator to its name.

… = *ptr

*ptr = …;

int

int *

18

0x5286

0x1015

ptr

num

Addresses

Values

0x1015

43 of 71

Pointers

CS-202 C. Papachristos

Indirection (Dereference) Operator ( * ) or “Value-Pointed-By”

At this point what follows depends on purpose of Dereferencing.

A Dereference can be in three “places”:

  • On the left hand side of the assignment operator.
  • On the right hand side of the assignment operator.
  • In an expression with no assignment operator (e.g. a cout statement).

44 of 71

Pointers

CS-202 C. Papachristos

Indirection (Dereference) Operator ( * ) or “Value-Pointed-By”

To refer to the Value-Pointed-By a pointer, we pre-pend the star (*) operator to its name.

int inVar = *ptr;

cout << *ptr << endl;

int

int *

18

0x5286

0x1015

ptr

num

Addresses

Values

0x1015

Access variable.

Get its value.

45 of 71

Pointers

CS-202 C. Papachristos

Indirection (Dereference) Operator ( * ) or “Value-Pointed-By”

To refer to the Value-Pointed-By a pointer, we pre-pend the star (*) operator to its name.

*ptr = 36;

int

int *

36

0x5286

0x1015

ptr

num

Addresses

Values

0x1015

Access variable.

Change its value.

46 of 71

Pointers

CS-202 C. Papachristos

Pointers at Work

int variable instantiation – Memory allocation

int x = 5;

Variable name

x

Memory Address

0x7f96c

Value

5

47 of 71

Pointers

CS-202 C. Papachristos

Pointers at Work

int Pointer variable instantiation – Value assignment by Reference (Address-Of)

int x = 5;

int * xPtr = &x; /* xPtr points to x */

Variable name

x

xPtr

Memory Address

0x7f96c

0x7f960

Value

5

0x7f96c

48 of 71

Pointers

CS-202 C. Papachristos

Pointers at Work

int variable instantiation – Value assignment by Dereferencing (Value-Pointed-By)

int x = 5;

int * xPtr = &x; /* xPtr points to x */

int y = *xPtr; /* y’s value is now ... */

Variable name

x

xPtr

y

Memory Address

0x7f96c

0x7f960

0x7f95c

Value

5

0x7f96c

0x7f96c

49 of 71

Pointers

CS-202 C. Papachristos

Pointers at Work

int variable instantiation – Value assignment by Dereferencing (Value-Pointed-By)

int x = 5;

int * xPtr = &x; /* xPtr points to x */

int y = *xPtr; /* y’s value is now ... */

Variable name

x

xPtr

y

Memory Address

0x7f96c

0x7f960

0x7f95c

Value

5

0x7f96c

0x7f96c

50 of 71

Pointers

CS-202 C. Papachristos

Pointers at Work

int variable instantiation – Value assignment by Dereferencing (Value-Pointed-By)

int x = 5;

int * xPtr = &x; /* xPtr points to x */

int y = *xPtr; /* y’s value is now ... */

Variable name

x

xPtr

y

Memory Address

0x7f96c

0x7f960

0x7f95c

Value

5

0x7f96c

0x7f96c

51 of 71

Pointers

CS-202 C. Papachristos

Pointers at Work

int variable instantiation – Value assignment by Dereferencing (Value-Pointed-By)

int x = 5;

int * xPtr = &x; /* xPtr points to x */

int y = *xPtr; /* y’s value is now 5 */

Variable name

x

xPtr

y

Memory Address

0x7f96c

0x7f960

0x7f95c

Value

5

0x7f96c

5

0x7f96c

52 of 71

Pointers

CS-202 C. Papachristos

Pointers at Work

int variable Value assignment – No address aliasing / No variable correlation

int x = 5;

int * xPtr = &x; /* xPtr points to x */

int y = *xPtr; /* y’s value is now 5 */

x = 3; /* y is still 5 */

Variable name

x

xPtr

y

Memory Address

0x7f96c

0x7f960

0x7f95c

Value

3

0x7f96c

5

0x7f96c

53 of 71

Pointers

CS-202 C. Papachristos

Pointers at Work

int variable Value assignment – No address aliasing / No variable correlation

int x = 5;

int * xPtr = &x; /* xPtr points to x */

int y = *xPtr; /* y’s value is now 5 */

x = 3; /* y is still 5 */

y = 2; /* x is still 3 */

Variable name

x

xPtr

y

Memory Address

0x7f96c

0x7f960

0x7f95c

Value

3

0x7f96c

2

0x7f96c

54 of 71

Pointer Arithmetic

Moving through an Array with Pointers

int num_array[10] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };

int* num_ptr;

num_ptr = num_array; //or equivalently, num_ptr = &num_array[0];

cout << *num_ptr;

0 Pointer points to Address of array 1st element.

CS-202 C. Papachristos

55 of 71

Pointer Arithmetic

Moving through an Array with Pointers

int num_array[10] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };

int* num_ptr;

num_ptr = num_array; //or equivalently, num_ptr = &num_array[0];

cout << *num_ptr;

num_ptr++;

cout << *num_ptr;

1 Pointer moves to point 1 position ahead (++) in memory,

therefore pointing to Address of array 2nd element.

CS-202 C. Papachristos

56 of 71

Pointer Arithmetic

Moving through an Array with Pointers

int num_array[10] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };

int* num_ptr;

num_ptr = num_array; //or equivalently, num_ptr = &num_array[0];

cout << *num_ptr;

num_ptr++;

cout << *num_ptr;

num_ptr += 8;

cout << *num_ptr;

9 Pointer moves to point 8 positions more ahead (+=8) in memory,

therefore pointing to Address of array 10th element.

CS-202 C. Papachristos

57 of 71

Pointer Arithmetic

Moving through an Array with Pointers

int num_array[10] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };

int* num_ptr;

num_ptr = num_array; //or equivalently, num_ptr = &num_array[0];

cout << *num_ptr;

num_ptr++;

cout << *num_ptr;

num_ptr += 8;

cout << *num_ptr;

num_ptr--;

cout << *num_ptr;

8 Pointer moves to point 1 position backwards (--) in memory,

therefore pointing to Address of array 9th element.

CS-202 C. Papachristos

58 of 71

Pointer Arithmetic

Moving through an Array with Pointers

int num_array[10] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };

int* num_ptr;

num_ptr = num_array; //or equivalently, num_ptr = &num_array[0];

cout << *num_ptr;

num_ptr++;

cout << *num_ptr;

num_ptr += 8;

cout << *num_ptr;

num_ptr--;

cout << *num_ptr;

num_ptr-=5;

cout << *num_ptr;

num_ptr = num_array;

cout << *num_ptr;

3 Pointer moves to point 4 positions more back (-=5) in memory,

therefore pointing to Address of array 4th element.

CS-202 C. Papachristos

59 of 71

Pointer Arithmetic

Moving through an Array with Pointers

int num_array[10] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };

int* num_ptr;

num_ptr = num_array; //or equivalently, num_ptr = &num_array[0];

cout << *num_ptr;

num_ptr++;

cout << *num_ptr;

num_ptr += 8;

cout << *num_ptr;

num_ptr--;

cout << *num_ptr;

num_ptr-=5;

cout << *num_ptr;

num_ptr = num_array;

cout << *num_ptr;

0 Pointer reassigned to points again� to Address of array 1st element.

CS-202 C. Papachristos

60 of 71

Functions – Pass-by-Address

CS-202 C. Papachristos

Pointers as Function Parameters

Common Paradigm:

  • A function that modifies more than one values.

Example: How to multiply Two int values by an order of magnitude.

void increaseOrder( <two ints> ) {

// multiply first int by 10

// multiply second int by 10

// have the values persist after control is return’ed -- how?

}

  • Can’t use Pass-by-Value, then return & assign method.

return will only give back One value.

  • Can use Pass-by-Reference (working directly on passed arguments).

  • But also …

61 of 71

Functions – Pass-by-Address

CS-202 C. Papachristos

Pointers as Function Parameters

Common Paradigm:

  • A function that modifies more than one values.

Example: How to multiply Two int values by an order of magnitude.

Work on an Address basis.

void increaseOrder( int * ptr1, int * ptr2) {

// multiply by ten the values of the ints that ptr1, ptr2 point to

*ptr1 = *ptr1 * 10;

*ptr2 *= 10;

// return nothing

}

62 of 71

Functions – Pass-by-Address

CS-202 C. Papachristos

Pointer Parameters in Functions

Function Declaration:

void increaseOrder(int * ptr1, int * ptr2);

Function Call:

int firstNum = 25;

int secondNum = 350;

int * firstNumPtr = &firstNum;

int * secondNumPtr = &secondNum;

increaseOrder(firstNumPtr, secondNumPtr);

increaseOrder(&firstNum, &secondNum);

increaseOrder(firstNumPtr, &secondNum);

Note:

increaseOrder(&25, &350); Note: Won’t work, these are Literals!

or

or

error: lvalue required as unary '&' operand”

63 of 71

Functions – Pass-by-Address

CS-202 C. Papachristos

Functions and Arrays

Arrays “Decay” into Pointers, they are always Passed-by-Address to functions.

  • Program does not make a copy of an array.
  • Changes made to an array inside a function will persist after the function exits.

Remember entire Arrays as Function Arguments:

double array[10] = {}; // braced initializer for zero-initialization

void arrayWholeFunction(double vals [], int num);

void arrayWholeFunction(double * vals , int num);

arrayWholeFunction(array, 10);

arrayWholeFunction(&array[0], 10);

or

or

Valid Definitions

by-Address (name)

by-Address-of (1st element)

64 of 71

Functions – Pass-by-Address

CS-202 C. Papachristos

Functions and C-strings

C-strings are char type arrays, they are always Passed-by-Address to functions.

  • Same as any other array.

Remember entire Arrays as Function Arguments (nothing more special):

char mystring[] = "Hello world!"; // string literal for initialization

void capitalizeFirstLetter(char text []);

void capitalizeFirstLetter(char * text );

capitalizeFirstLetter(mystring);

capitalizeFirstLetter(&mystring[0]);

or

or

Valid Definitions

by-Address (name)

by-Address-of (1st element)

65 of 71

Comprehensive Pointer Example

CS-202 Lab Sections

#include <iostream>

using namespace std;

const int MAX_STR_SIZE = 255;

void cStringPrint(char * cstr);

int main(){

char my_cString[MAX_STR_SIZE] = "Hello World!";

cStringPrint ( my_cString );

return 0;

}

void cStringPrint(char * cstr){

while( *cstr ){

cout << *cstr++ ;

}

}

A C-string i.e. char array

A Function with a char* parameter

A Function that:

  • Iterates through an array by�employing Pointer-Arithmetic (++)
  • Accesses elements of an array by�employing Pointer-Dereferencing (*)

Equivalent to: cout << *cstr ;

cstr++;

66 of 71

Overview: Parameters in Functions

CS-202 C. Papachristos

i) Pass-by-Value

  • The “default” way.
  • Implies Data Copy operation.

void printVal (int x);

int x = 5;

int * xPtr = &x;

printVal(x);

printVal(*xPtr);

Valid Calls

67 of 71

Overview: Parameters in Functions

CS-202 C. Papachristos

ii) Pass-by-Address

  • Uses pointers, and uses (*) and (&) operators.
  • Address passed (via Pointer value), Data Copy unnecessary.

void changeVal (int * x);

int x = 5;

int * xPtr = &x;

changeVal(&x);

changeVal(xPtr);

Valid Calls

68 of 71

Overview: Parameters in Functions

CS-202 C. Papachristos

ii) Pass-by-Address

  • Uses pointers, and uses (*) and (&) operators.
  • Address passed (via Pointer value), Data Copy unnecessary.

void changeVal (int * x);

int x = 5;

int * xPtr = &x;

changeVal(&x);

changeVal(xPtr);

Valid Calls

Note:

Have to check for NULL pointer inside function calls !

No guarantees pointer is valid.

69 of 71

Overview: Parameters in Functions

CS-202 C. Papachristos

iii) Pass-by-Reference

  • Uses (&) operator once (function declaration).
  • Actual Argument passed, Data Copy unnecessary.

void changeByRef (int & x);

int x = 1;

int & xAlias = x;

changeByRef(x);

changeByRef(xAlias);

Valid Calls

70 of 71

Overview: Parameters in Functions

CS-202 C. Papachristos

iii) Pass-by-Reference

  • Uses (&) operator once (function declaration).
  • Actual Argument passed, Data Copy unnecessary.

void changeByRef (int & x);

int x = 1;

int & xAlias = x;

changeByRef(x);

changeByRef(xAlias);

Valid Calls

Note:

Variable might be changed.

Have to bear in mind the function prototype !

71 of 71

Time for Questions !

CS-202

CS-202 C. Papachristos