C++ Functions
Pointers & References
C. Papachristos
Robotic Workers Lab
University of Nevada, Reno
CS-202
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.
Today’s Topics
CS-202 C. Papachristos
C++ Functions
Prototype
Definition
Call
Pointers
References
Functions
CS-202 C. Papachristos
Function Parts
Function Declaration (Prototype)
Function Definition (Implementation)
Function Call
Functions
CS-202 C. Papachristos
Function Declaration (Prototype)
Gives compiler information about 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
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;
}
Placed AFTER the function main() (NOT inside).
Function Block :
Brace-enclosed
Functions
CS-202 C. Papachristos
Function Call
Much like a standard C call:
char printSum[256];
double returnSum = sprintSum(10, 0.1, printSum);
(Assigned to variable returnSum)
Arguments:
(Can also pass variables – do they have to be int and double?)
(Has to match char [] type – formally char *.)
#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
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.
Typical use: guard statements ( if(somethingWrong) return; ).
Functions
CS-202 C. Papachristos
Function Parameters / Arguments
(Function) Parameter:
(Function) Argument:
Multiple Parameters / Arguments:
double precisionSum(double a, double b);
cout << precisionSum(0.1 * 1000000, 1e-3);
100.001
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);
Functions
CS-202 C. Papachristos
Function Pre / Post - Conditions
Include function headers with intuitive documentation in your code.
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:
Functions
CS-202 C. Papachristos
C++ Function Libraries
Full of useful functions!
Must “#include” appropriate library.
<cmath> ~ <math.h>
<cstdlib> ~ <stdlib.h>
<cstring> ~ <string.h>
(e.g. std::cout, std::cin)
<iostream>
C++
C analog
Table from:
Absolute C++
Copyright © 2016
Pearson, Inc.
All rights reserved.
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
Note:
Functions in C++ can only return one thing!
(one type of variable)
Functions
CS-202 C. Papachristos
Functions & Parameters
Methods of passing arguments to functions:
A “Copy” of the value of the actual argument is used.
The “Actual” argument itself is used.
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.
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.
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
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.
Function has no access to Actual argument from caller.
Call:
int enrolled = 99;
addOne(enrolled);
enrolled = addOne(enrolled);
enrolled: 99
enrolled: 100
Functions – Pass-by-Value
CS-202 C. Papachristos
Pass-by-Value
A common mistake:
double fee(int hoursWorked, int minutesWorked)
{� int quarterHours; � int minutesWorked � }
Compiler error: "error: declaration of 'int minutesWorked' shadows a parameter…"
Local Variable
Shadowing
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.
Rules:
Once initialized, they are forever tied to the thing they reference.
No such thing as a NULL reference (unlike a NULL pointer).
(They look like normal variables)
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.
Rules:
[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)
Functions – Pass-by-Reference
CS-202 C. Papachristos
Pass-by-Reference ( & )
Provides access to caller’s Actual argument.
Typically used for input function.
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
Functions – Pass-by-Reference
CS-202 C. Papachristos
Pass-by-Reference ( & )
What is really passed in:
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
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;
}
Functions – Pass-by-Reference
CS-202 C. Papachristos
Reference Caveats
Reference-Type variable declaration with the ampersand (&) symbol.
int & xRef = x;
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";
Functions – Pass-by-Reference
CS-202 C. Papachristos
Reference Caveats
Reference declaration the ampersand (&) symbol.
int & xRef = x;
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";
Functions – Pass-by-Reference
CS-202 C. Papachristos
const-Reference Parameters (const &)
Calling-by-Reference arguments is inherently “dangerous”:
Common technique to “protect” data:
The keyword const.
void sendConstRef(const int & par1, const int & par2);
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);
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
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.
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
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.
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)
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
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 !)
Pointers
CS-202 C. Papachristos
Pointer Utility
Pointers are incredibly useful in programming.
Modify multiple arguments.
Use and modify arrays as arguments.
Pointers
CS-202 C. Papachristos
Pointer Declaration
A pointer is just like any regular variable. It has:
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 !
Pointers
CS-202 C. Papachristos
Pointer Declaration
Valid pointers declaration / creation statements:
int *ptr1;
int* ptr2;
int * ptr3;
int*ptr4;
Note:
int * ptr1, * ptr2, * ptr3;
int * ptr1, ptr2, ptr3;
Just avoid the last one.
Looks right, but no,� this declares an int * and 2 ints
int
Pointers
CS-202 C. Papachristos
Pointer Value
As earlier stated, pointers are “Just Variables”.
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
Pointers
CS-202 C. Papachristos
Pointer Assignment
Value (pointed-to Address) assignment:
int x = 5;
int * xPtr = NULL;
xPtr = &x;
int * yPtr;
yPtr = xPtr;
Simple grammar:
“Pointer-value gets assigned the Address-of variable x”.
Pointers
CS-202 C. Papachristos
Pointer Assignment
Value (pointed-to Address) assignment:
Address-Of a Value is not enough for a valid assignment!
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.”
int
Pointers
CS-202 C. Papachristos
Pointer Assignment
Assignment means telling the pointer what memory address to point to:
int num = 18;
int * ptr = #
int *
18
0x5286
0x1015
ptr
num
Addresses
Values
Where it “lives” in memory.
Where it points-to
in memory
0x1015
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
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
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”:
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.
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.
Pointers
CS-202 C. Papachristos
Pointers at Work
int variable instantiation – Memory allocation
int x = 5;
Variable name | x |
Memory Address | 0x7f96c |
Value | 5 |
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 |
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
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
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
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
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
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
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
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
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
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
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
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
Functions – Pass-by-Address
CS-202 C. Papachristos
Pointers as Function Parameters
Common Paradigm:
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?
}
return will only give back One value.
Functions – Pass-by-Address
CS-202 C. Papachristos
Pointers as Function Parameters
Common Paradigm:
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
}
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”
Functions – Pass-by-Address
CS-202 C. Papachristos
Functions and Arrays
Arrays “Decay” into Pointers, they are always Passed-by-Address to functions.
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)
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.
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)
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:
Equivalent to: cout << *cstr ;
cstr++;
Overview: Parameters in Functions
CS-202 C. Papachristos
i) Pass-by-Value
void printVal (int x);
int x = 5;
int * xPtr = &x;
printVal(x);
printVal(*xPtr);
Valid Calls
Overview: Parameters in Functions
CS-202 C. Papachristos
ii) Pass-by-Address
void changeVal (int * x);
int x = 5;
int * xPtr = &x;
changeVal(&x);
changeVal(xPtr);
Valid Calls
Overview: Parameters in Functions
CS-202 C. Papachristos
ii) Pass-by-Address
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.
Overview: Parameters in Functions
CS-202 C. Papachristos
iii) Pass-by-Reference
void changeByRef (int & x);
int x = 1;
int & xAlias = x;
changeByRef(x);
changeByRef(xAlias);
Valid Calls
Overview: Parameters in Functions
CS-202 C. Papachristos
iii) Pass-by-Reference
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 !
Time for Questions !
CS-202
CS-202 C. Papachristos