introduction to c++ part ii version 1.3. topics c++ functions -- passing by value in c++ -- passing...

Post on 20-Jan-2016

222 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Introduction to C++Part II

Version 1.3

Topics

C++ Functions -- passing by value in C++ -- passing by reference in C++ -- passing by address in C++C++ Arrays -- char arrays -- vectors

C++ Functions

What we called methods in C# are referred to as functions in C++.

The C# compiler is a multipass compiler, and so it is not necessary to “declare” a method before it is used. This is not true in C++.

Function Prototypes

In C++, we must declare a function by writing afunction prototype in the code someplace before the function is ever called. For stand-alone functionswe normally write the function prototypes before main( ).

#include <iostream>using namespace std;

void printMe(int);

int main( ){

int a = 5;printMe(a);system("PAUSE");return 0;

}

void printMe(int num){

cout << "\nNumber = " << num << endl;}

The function prototype

Calling the function

The function implementation

We usually include the function prologuewith the function prototype.

#include <iostream>using namespace std;

// The printMe function// Purpose: outputs the parameter// Parameter: The value to be output as an integer// Returns: nothingvoid printMe(int);

int main( ){

int a = 5;printMe(a);system("PAUSE");return 0;

}

void printMe(int num){

cout << "\nNumber = " << num << endl;}

Passing Parameters by Value

C#void swap(int num1, int num2){ int temp = num1; num1 = num2; num2 = temp;}

Passing parameters by value is basicallythe same in C++ and C#

C++void swap(int num1, int num2){ int temp = num1; num1 = num2; num2 = temp;}

What is the problem here?

void swap(x,y); //function call

Passing Parameters by Reference

C#void swap( ref int num1, ref int num2){ int temp = num1; num1 = num2; num2 = temp;}

Passing parameters by reference is slightlydifferent in C++ and C#

C++void swap(int& num1, int& num2){ int temp = num1; num1 = num2; num2 = temp;}

void swap(x,y); //function call

Passing Parameters by Address

C#void swap( ref int num1, ref int num2){ int temp = num1; num1 = num2; num2 = temp;}

Passing parameters by address is completelydifferent in C++ and C# doesn’t allow it, normally

C++void swap(int* num1, int* num2){ int temp = *num1; *num1 = *num2; *num2 = temp;}

void swap(&x,&y); //function call

In C++, there are no reference data typesas there are in C#. Everything is passed byvalue, unless you explicitly tell the compilerto pass by reference.

Passing by const Refernce

C++ has a notion of constantness that does not existin C#. When passing a parameter by reference, it ispossible to have a side effect that changes the data inthe calling function. Generally side effects are notwanted. To avoid side effects, we pass byconstant reference.

void printMe( const Employee& joe);

This is a common idiom in C++. It allows us to pass an object without having to make a copy of theobject (which is expensive), but avoids any changesto the object by the function.

If a member function does not change anything(for example, a “getter”), then you shouldmake the function a constant function.

string Employee::getAddress( ) const;

Arrays in C++

Arrays in C++

There is a major difference in how arrays aredefined in C# and C++. In C#, arrays are true objects. In C++ they are not objects.

examScores

89

94

78

93

75

99

82

77

53

87

An array is a list of values … not an object

All values must be of the same type

Values are stored in consecutivememory locations

The position where a value is storedin an array is given by its index.We sometimes refer to this as thesubscript.

Indexing always begins with zero

To access an element of an array, weuse the array name, followed by the indexinside of square brackets

0

1

2

3

4

5

6

7

8

9

Declaring an ArrayexamScores

0

1

2

3

4

5

6

7

8

9

int examScores[10];

the declaration

data type of array elementsarray size

Good programming style uses a constant for thearray size. For example

const int SIZE = 10;int examScores[SIZE];

examScores

89

94

78

93

75

99

82

77

53

87

0

1

2

3

4

5

6

7

8

9

index

value of examScores[4]

Accessing array elements in C++ is identical to C#

Out of Bounds Errors

When a C++ program is executing, it does not noticewhen a calculation results in an array index that isout of bounds. The address of the element is calculatedand that place in memory is accessed, even if it does not belong to the array! This is much different than what happens in C#.

someInts 0

1

2

3

4

0

1

2

3

4

index

int someInts[5], badNum;

badnum = 100;for ( int indx = 0; indx <=5; indx++){ someInts[indx] = indx;}

someInts +4

someInts +8

someInts +12

someInts +16

badNum 1005

Notice that we over-wrote the variablebadNum with the value of 5! This destroysthe original value in badNum.

Initializer lists

int examScores [ ] = { 87, 83, 94, 99, 74, 66, 88 };

the array size is automatically determined by the number of items in the initializer list

int examScores [10] = { 0}; //intialize all values to 0

Since an array is not an object, there is nomember data nor any methods that returnthe size of the array. When passing an arrayas a parameter, it is common to pass the sizeof the array as an additional parameter.

Two Dimensional Arrays

rows

columns

How we think of a two dimensional array

examScores

student 1

student 2

student 3

exam 1 exam 2 exam 3 exam 4

78 89 65 97

76 79 82 85

83 89 91 90

An Array of Arrays

student 1

student 2

student 3

exam 1 exam 2 exam 3 exam 4

78 89 65 97

76 79 82 85

83 89 91 90

int main( ){ // declare an array 3 x 4

int examScores[ ][4]= { {78, 89, 65, 97}, {76, 79, 82, 85},

{83, 89, 91, 90} };

const int STUDENT = 3;const int EXAMS = 4;

for ( int i = 0; i < STUDENT; i++ ){ int sum = 0; for ( int j = 0; j < EXAMS; j++ ) sum = sum + examScores [ i ][ j ];

float avg = ((float)sum)/EXAMS; cout << “Student # “ << (i+1) << “: “ << avg << “\n”;

}}

Multi-dimensional array as a parameter…

We do not give the size of the first dimension of anarray when passing it, but we do give the sizes ofthe remaining dimensions. The size of the first dimensionis passed as a separate argument.

void getPage (char p[][100], int sizeOne);

We have been using the C++ Stringclass to represent strings of characters.Although this is the most convenient wayto represent character strings, the C++language also represents character stringsas arrays of type char.

Char Arrays

someText

0

1

2

3

4

5

h

e

l

l

o

\0

The terminal character in the array is thenull terminating character, \0.

This is called a null terminated string, ora C-string (this is the only way that acharacter string could be represented in the C language).

Functions that operate on C-strings look for the null terminating character to know where the end of the string is.

When creating an array to store a character string,always be sure that there is room for the nullterminating character.

Note that is possible to have an arrayof characters that is not a C-String.

char firstName[20] = “John”;

firstName

0

1

2

3

4

5

J

o

h

n

\0

?

. . .

?

?

when initialized this way, thenull terminating character isautomatically added at the end.

char lastName[20] = {‘S’,’m’,’i’,’t’,’h’};

lastName

0

1

2

3

4

5

S

m

i

t

h

?

. . .

?

?

when initialized this way, no nullterminating character is added.This is just a simple array ofcharacters. It is not a C-String!

Char Arrays and LoopsYou can treat a char array exactly like any other array.

You can use index notation to access individual array elements

lastName[n] = ‘ t ’;

You can use loops to manipulate arrays elements.

for (int n = 0; n < SIZE; n++){ lastName[n] = ‘ - ’;}

But … be careful not to accidentally replace the null terminating character with some other character.

AssignmentAlthough you can use the assignment operatorwhen initializing an array, you cannot use theassignment operator anywhere else with acharacter array. For example, the following isillegal:

char aString[10];aString = “Hello”;

Make sure that you do not leave an array withgarbage values, i.e. char aString[10];

memset(aString,’\0’,sizeof(aString)); // intializesthe array to all nulls as does:

aString[10] = {‘\0’}’

strcpy Function

The easiest way to assign a value to a C-Stringis to use the strcpy function.

To use strcpy you must use the include directive

#include <cstring>

No using statement is required, the definitionsin <cstring> are in the global namespace.

Security IssuesIncorrect use of string functions has caused many security problems because of buffer over-runs. To prevent these problems use:

“n” versions of functions, like strncpy – you must ensure that string is null-terminated. If it is not, do it manually after the copy.

“l” versions of functions, like strlcpy – these are not part of the standard library, but source code is available from BSD

“_s” versions of functions, like strcpy_s – available with Microsoft development tools, might be included in standard libraries later.

strcpy (aString, “Hello”);

copies the char string Hello into aString.includes a null terminating character.

Examples

strcpy (aString, bString);

copies the contents of bString into aString.

strncpy (aString, bString, 9);

copies at most 9 characters from bString into aString.

by making the last parameter oneless than the size of aString, you can make the copy safe … i.e. it will not over-run the array.

Equality

Comparing two C-Strings using the equalityoperator will compile without errors and willexecute, but will not give you the results youexpect.

char aString[ ] = “abc”;char bString[ ] = “abc”;

if ( aString == bString ){ …

strcmp Function

To compare two C-Strings, use the strcmpfunction.

You must #include <cstring> to use thisfunction.

strcmp(strng1, strng2);

returns a value of zero if the strings are equal returns a negative value if strng1 < strng2 returns a positive value if strng1 > strng2

comparison is done in lexicographic order.

Other <cstring> functions

strcat (strng1, strng2);

concatenates strng2 to the end of strng1.

strlen (aString);

returns the length of aString does not include the null terminating character

C-String Input and Output

You can use >> and << operators to input and output C-Strings.

To input a string containing blanks, youmust use cin.getline (a, n);

where a is a char array andn is an integer that indicates the maxnumber of characters to read. Note thatthe null terminating character fills oneof these character positions.

These techniques work on files as wellas standard input and output.

Character I/OSometimes it is useful to input and outputone character at a time.

cin.get(aChar);

reads one character into aChar.

cout.put (aChar);

writes the character in aChar tocout.

These work on any character, includingspaces and new-line characters.

Example

The following code will read one characterat a time from standard in and write it tostandard out, until a new-line character isencountered.

char symbol = ‘ ‘;do{ cin.get (symbol); cout.put (symbol);} while (symbol != ‘\n’);

Character Manipulation Functions

The following functions operate on characters. To useany of these you must

#include <cctype>

No using statement is required. The definitions in<cctype> are in the global namespace.

The ASCII Code Table

toupper (aChar);

returns the upper case value of aChar as an integer.

tolower (aChar);

returns the lower case value of aChar as an integer.

islower (aChar);

returns true of the value in aChar is lower case.

isalpha (aChar);

returns true if the value in aChar is a letter.

isdigit (aChar);

returns true if the value in aChar is a digit 0 through 9

isspace (aChar);

returns true if the value in aChar is white space.

Vectors

Vectors can be thought of as arrays that grow as required, while a program is executing.

Vectors are formed from a template class in theStandard Template Library (STL).

Declaring a Vector

#include <vector>using namespace std; . . .

vector <int> v;

the notation <int> defines the type of vector.In this case, we have declared a Vector of integers.

Accessing Vector Elements

You can use the square bracket notation [ ] to accesselements of a vector, just as you do for an array. Notehowever, that you can only access existing Vector elements this way, you cannot initialize them!

Initializing Vector Elements

To add an element to a Vector for the first time, youmust use the push_back function. push_back adds anelement in the next available position.

v.push_back ( 23 );

The size of a Vector

As noted, the size of a Vector changes as needed, toaccommodate new elements. The current size of aVector ( the number of elements in the Vector ) can befound by

unsigned int n = v.size( );

note that the size( ) function returns an unsigned int.This can be automatically converted to an int by mostcompilers. To be safe, do an explicit cast or use theunsigned int data type, as shown above.

Example

#include <iostream>#include <vector>using namespace std;

int main ( ){ vector<int> v; cout << “Enter a list of positive numbers.\n”; cout << “End the list with a negative number.\n”;

int next; cin >> next; while ( next > 0 ) { v.push_back( next ); cout << next << “ added to the Vector\n.”; cout << “v.size( ) = “ << v.size( ) << endl; cin >> next; }

cout << “You entered:\n”;for ( unsigned int i = 0; i < v.size( ); i++ ) cout << v[ i ]; return 0;}

top related