Week 14 - Monday CS222.

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Week 13 - Wednesday.  What did we talk about last time?  Networking.
Object Oriented Programming Elhanan Borenstein copyrights © Elhanan Borenstein.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Lecture 19 CIS 208 Wednesday, April 06, Welcome to C++ Basic program style and I/O Class Creation Templates.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Week 15 - Friday.  What did we talk about last time?  Review up to Exam 2.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
C++ Programming Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Week 13 - Friday.  What did we talk about last time?  Server communications on a socket  Function pointers.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Lecture 3: Getting Started & Input / Output (I/O)
Chapter 15 - C++ As A "Better C"
CSE 374 Programming Concepts & Tools
C Structures and Memory Allocation
Week 2 - Wednesday CS 121.
Introduction to C++ (Extensions to C)
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Strings CSCI 112: Programming in C.
C++ Templates.
Introduction to C++ Systems Programming.
Motivation and Overview
Functions, Part 2 of 2 Topics Functions That Return a Value
C Programming Tutorial – Part I
Week 14 - Wednesday CS222.
Working with Strings Lecture 2 Hartmut Kaiser
The Selection Structure
CSC113: Computer Programming (Theory = 03, Lab = 01)
C Short Overview Lembit Jürimägi.
Student Book An Introduction
C Basics.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Week 4 - Monday CS222.
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
C Stuff CS 2308.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Pointers, Dynamic Data, and Reference Types
More About Data Types & Functions
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Working with Strings Lecture 2 Hartmut Kaiser
Arrays Kingdom of Saudi Arabia
Functions, Part 2 of 3 Topics Functions That Return a Value
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Constructors and Other Tools
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Chapter 9 Strings Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
7 Arrays.
Chapter 15 - C++ As A "Better C"
Arrays Arrays A few types Structures of related data items
C++ Programming Basics
Programming Languages and Paradigms
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Instructor: Dr. Michael Geiger Spring 2017 Lecture 12: Exam 1 Preview
Functions, Part 2 of 3 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
Introduction to Classes and Objects
Presentation transcript:

Week 14 - Monday CS222

Last time What did we talk about last time? Server sockets Lab 13

Questions?

Project 6

Function Pointers

Function pointers C can have pointers to functions You can call a function if you have a pointer to it You can store these function pointers in arrays and structs They can be passed as parameters and returned as values Java doesn't have function pointers Instead, you pass around objects that have methods you want C# has delegates, which are similar to function pointers

Why didn't we cover these before? K&R group function pointers in with other pointers I put them off because: They are confusing The syntax to declare function pointer variables is awful They are not used very often They are not type-safe But you should still know of their existence!

Declaring a function pointer The syntax is a bit ugly Pretend like it's a prototype for a function Except take the name, put a * in front, and surround that with parentheses #include <math.h> #include <stdio.h> int main() { double (*root) (double); //pointer named root root = &sqrt; //note there are no parentheses printf( "Root 3 is %lf", root(3) ); printf( "Root 3 is %lf", (*root)(3) ); //also legal return 0; }

A more complex example int** (*pointer)(char, double, void*); Some function's prototype: Its (worthless) definition: A compatible function pointer: Function pointer assignment: int** fizbin(char letter, double length, void* thing); int** fizbin(char letter, double length, void* thing) { return (int**)malloc(sizeof(int*)*50); } int** (*pointer)(char, double, void*); pointer = fizbin;

Two styles Just to be confusing, C allows two different styles for function pointer assignment and usage #include <math.h> #include <stdio.h> int main() { int (*thing) (); //pointer named thing thing = &main; //looks like regular pointers thing = main; //short form with & omitted (*thing)(); //normal dereference thing(); //short form with * omitted return 0; }

Motivation Why would we want function pointers?

Motivation Consider a bubble sort that sorts an array of strings The book uses quicksort as the example, but I don't want to get caught up in the confusing parts of quicksort void bubbleSort(char* array[], int length) { char* temp; int i, j; for(i = 0; i < length – 1; i++ ) for(j = 0; j < length – 1; j++ ) if(strcmp(array[j],array[j+1]) > 0) temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; }

Motivation Now consider a bubble sort that sorts arrays of pointers to single int values void bubbleSort(int* array[], int length) { int* temp; int i, j; for(i = 0; i < length – 1; i++ ) for(j = 0; j < length – 1; j++ ) if(*(array[j]) > *(array[j+1])) temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; }

A rectangle struct Let's pause for a moment in our consideration of sorts and make a struct that can contain a rectangle typedef struct { double x; //x value of upper left double y; //y value of upper left double length; double height; } Rectangle;

Motivation Now consider a bubble sort that sorts arrays of pointers to Rectangle structs Ascending sort by x value, tie-breaking with y value void bubbleSort(Rectangle* array[], int length) { Rectangle* temp; int i, j; for(i = 0; i < length – 1; i++ ) for(j = 0; j < length – 1; j++ ) if(array[j]->x > array[j+1]->x || (array[j]->x == array[j+1]->x && array[j]->y > array[j+1]->y)) temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; }

Universal sort We can write a bubble sort (or ideally an efficient sort) that can sort anything We just need to provide a pointer to a comparison function void bubbleSort(void* array[], int length, int (*compare)(void*, void*)) { void* temp; int i, j; for( i = 0; i < length – 1; i++ ) for(j = 0; j < length – 1; j++ ) if(compare(array[j],array[j+1]) > 0) temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; }

Typechecking Function pointers don't give you a lot of typechecking You might get a warning if you store a function into an incompatible pointer type C won't stop you And then you'll be passing who knows what into who knows where and getting back unpredictable things

Simulating OOP C doesn't have classes or objects It is possible to store function pointers in a struct If you always pass a pointer to the struct itself into the function pointer when you call it, you can simulate object-oriented behavior It's clunky and messy and there's always an extra argument in every function (equivalent to the this pointer) As it turns out, Java works in a pretty similar way But it hides the ugliness from you

C++

Overview C++ is based on C and easier to use You can declare variables anywhere Not the case in the C89 standard (where all variables had to be declared right after a block starts), but our gcc is following the C99 standard It has function overloading Most people think the I/O is cleaner The big addition is OOP through classes It's an approximate superset of C that includes most C structures

Compiling C++ gcc used to stand for the GNU C Compiler When it became a suite of tools used for things other than C, they changed the name to the GNU Compiler Collection The compiler for C++ is called g++ and is part of gcc, but it may need to be installed separately and doesn't come on all Linux installations by default C++ files have the extensions .cc, .cpp, .cxx, .c++, and .C I prefer .cpp, but .cc is also common g++ thing.cpp –o program

C++ is kind of an abomination C has too many ways to do things, but C++ is an order of magnitude worse Syntax is a big mess of overlapping, ambiguous ideas Which only got worse in the C++11 standard, which we aren't talking about C++ tried to be reverse compatible with C, but not strictly true It tried to be object-oriented, but not strictly true The Standard Template Libraries are hideous compared to the Java Collection Framework At the time, it was the best choice available for OOP, and now we're stuck with it

Hello, World in C++ It's not too different from C We need different headers for C++ I/O #include <iostream> using namespace std; int main() { cout << "Hello, world!" << endl; return 0; }

Output in C++ Output uses the cout object (of type ostream) Instead of using formatting strings, cout uses the idea of a stream, where objects are placed into the stream separated by the extraction operator << The endl object adds a newline to the stream Of course, "\n" works too int x = 50; cout << "There are " << x << " ways to leave your lover." << endl;

Formatting output Basic output is easier What about setting the width or precision? You need to include the iomanip header Put setw( width ) in the stream to make the items take up the specified width Put setprecision( precision ) in the stream to show a certain number of decimal places Put fixed to force it to pad with zeroes when there isn't enough precision double dollars = 2.0; cout << "Give me $" << setw(10) << fixed << setprecision(2) << dollars << setw(0) << "!" << endl; //printf equivalent printf("Give me $%10.2f!\n", dollars);

Input in C++ Input uses the cin object (of type istream) cin also uses the idea of a stream, where items are read from the stream and separated by the insertion operator >> It reads items using whitespace as the separator, just like scanf() int x = 0; int y = 0; int z = 0; cout << "Enter the x, y, and z values: "; cin >> x >> y >> z;

The string class Like Java, C++ has a class for holding strings, which makes life much easier It's called string (with a lower case 's') You must include <string> to use it Unlike String in Java, string is mutable You can use array-style indexing to get and set individual characters string a = "Can I kick it?"; string b = "Yes, you can!"; string c = a + " " + b; c[0] = 'D'; c[1] = 'i'; c[2] = 'd'; cout << c << endl; //prints Did I kick it? Yes, you can!

The std namespace Java uses packages to keep different classes with the same name straight C++ uses namespaces The standard library includes I/O (<iostream>), the string class (<string>), STL containers (<vector>, <list>, <deque>, and others) If you use these in your program, put the following after your includes The alternative is to specify the namespace by putting the it followed by two colons before the class name using namespace std; std::string name = "Ghostface Killah";

Functions in C++ Regular C++ functions are very similar to functions in C A big difference is that prototypes are no longer optional if you want to call the function before it's defined Unlike C, function overloading allowed: int max(int a, int b) { return a > b ? a : b; } int max(int a, int b, int c) return max( a, max( b, c));

Pass by reference In C, all functions are pass by value If you want to change an argument, you have to pass a pointer to the value In C++, you can specify that a parameter is pass by reference Changes to it are seen on the outside You do this by putting an ampersand (&) before the variable name in the header void swap(int &a, int &b) { int temp = a; a = b; b = temp; }

Pass by reference continued Pass by reference is a great tool You don't have to pass nearly as many pointers If you want to change a pointer, you can pass it by reference instead of passing a pointer to a pointer It does allow more mistakes Leave off the ampersand and your function does nothing Change things you didn't intend to change You cannot pass a literal by reference swap(3, 9); //doesn't compile

Default parameter values C++ also allows you to specify default values for function parameters If you call a function and leave off those parameters, the default values will be used Default parameters are only allowed for the rightmost grouping of parameters void build(int width = 2, int height = 4) { cout << "We built this house with " << width << " by " << height << "s."; } build(); //We built this house with 2 by 4s. build(3); //We built this house with 3 by 4s. build(6, 8); //We built this house with 6 by 8s.

C++ example Let's write a complete C++ program that reads in: A string An integer Then, it prints out the string however many times the integer specified

More C++

The new keyword When you want to dynamically allocate memory in C++, you use new (instead of malloc()) No cast needed It "feels" a lot like Java int* value = new int(); //make an int int* array = new int[100]; //array of ints Wombat* wombat = new Wombat(); //make a Wombat Wombat* zoo = new Wombat[100]; //makes 100 Wombats with the default constructor

The delete keyword When you want to free dynamically allocated memory in C++, use delete (instead of free()) If an array was allocated, you have to use delete[] int* value = new int(); //make an int delete value; Wombat* wombat = new Wombat(); delete wombat; Wombat* zoo = new Wombat[100]; delete[] zoo; //array delete needed

C standard libraries You can compile C code with C++ Weird things can happen, but we aren't going into those subtle issues However, you now know and love the standard C libraries You can use them in C++ too You just have to include different header files C Library Header C++ Equivalent Purpose ctype.h cctype Character manipulation limits.h climits Constants for integer limits math.h cmath Math functions stdio.h cstdio C I/O functions stdlib.h cstdlib Random values, conversion, allocation string.h cstring Null-terminated string manipulation time.h ctime Time functions

Structs in C++ A struct in C++ is actually just a class where all the members are public You can even put methods in a struct in C++ Otherwise, it looks pretty similar You don't have to use the struct keyword when declaring struct variables Except in cases when it is needed for disambiguation

Example Here's a TreeNode struct in C++ Write a tree insertion with the following signature struct TreeNode { int value; TreeNode* left; TreeNode* right; }; void insert(TreeNode* &root, int data);

ABET Evaluations

Upcoming

Next time… OOP in C++ C++ madness Templates in C++

Reminders Keep working on Project 6