C++ Lect3 Intro
C++ Lect3 Intro
Type bool
bool done;
done = true;
done = false;
if (done) { ... }
Searching:
s1.find(s2, j); // returns smallest index >= j where s2 occurs
within s1, or string::npos if not found. Return value is of type
string::size_type.
int x;
int& ref = x; // ref is another name for x;
ref =23;
cout << x << endl;
23
void swap(int x, int y)
{ int t; t = x; x = y; y = t; }
Output: 20 30
swap(u, v);
Output: 30 20
Returning references
Bad:
int& val()
{ int j;
j = 20;
return j;
}
k = val();
What’s wrong?
OK:
int & val(int a[ ], int index)
{
return a[index – 1];
}
printItem(“bananas”, 3, 10);
printItem(“pears”, 2);
printItem(“cucumbers”);
Function overloading
• We can use the same name to denote different functions as long as
they differ in the number of arguments and/or the type of the
arguments.
• A function’s signature is its name plus the number of arguments,
types of the arguments, and order of the arguments.
• For example, f(int, int), f(int, double), f(double), f (int)
f(3, 4) -> 7
f(3, 2.0) -> 6.0
f(3.0) -> 9.0
Dynamic allocation
delete p;
delete [ ] a;
Exceptions
• Traditionally, functions used special return
values to signify that an abnormal condition
had occurred.
• Exception handling in C++ is done via
exception throwing. When a function wants
to signify that an abnormal condition has
occurred, it throws an exception.
• In order to be notified of the exception, the
caller calls the function within a try block.
• The exception is caught by a catch block.
try {
f( ); // call function f that may throw
// exception
}
catch (T1 excpt) {
// Code to handle excpt having type T1
}
catch(T2 excpt) {
// Code to handle excpt having type T2
}
...
int main( )
{ int ret;
try {
ret = f(0);
}
catch(int x) {
cout << “Exception of type int caught: “ << x << endl;
}
catch(const char *s) {
cout << “Exception of type C string caught: “ << s << endl;
}
}
Some common exceptions
• #include <stdexcept>
• out_of_range: Thrown by string operations like erase, insert, replace and
substr when the first argument (starting position) is out of bounds.
• bad_alloc: Thrown by new if there is no memory left to satisfy the request
for dynamically allocated storage. (The old malloc returns a null pointer
instead).
For example:
try {
s.erase(10, 4);
}
catch(out_of_bounds) { // triggered if position 10 in s does not exist
cerr << “Bad index\n”;
exit(1);
}