








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









CS106 Handout # J Zelenski Jan 9, 2008
CS106B/X are taught using the C++ programming language, whereas our CS106A course uses Java. Becoming exposed to another language is an excellent way to broaden your experience while simultaneously preparing for the real world where much coding is done in C/C++. Our first goal is thus to orient you in C++. Don't let this intimidate you— C++ is syntactically similar to Java/C/C# and the core programming skills you've learned (decomposition, testing, debugging, algorithm design, etc.) are quite transferable, no matter what language you've worked in. Given the many small details and a few significant issues to cover, our first few lectures are focused on developing your "C++ legs". Although C++ is a complex and full-featured language, we will only incorporate those features that fit well with our pedagogical course goals, so no need to worry about having to learn an entire second language. This handout points out the Java/C++ differences most relevant to our course. These are just the highlights and although we will skim these topics in lecture, plan on working through the first three chapters of the reader on your own to get the full story with additional in-depth examples. A little history The C programming language originated around 1970 and was designed for professional programmers writing tight low-level code. The language is known for its terseness, limited support libraries, and runtime efficiency. It is known as an unsafe language because it makes tradeoffs that value efficiency over safety (for example, access to array elements is not bounds-checked) and gives the programmer unfettered access to do what they like (e.g. pointers and typecasts). C became quite popular and even today is still one of the dominant languages in use. It is a good tool for an experienced programmer, but not as appropriate for the rest of us mere mortals who could use some safety goggles to go with our blowtorch. C++ arrives on the scene in the 80s designed as “a better C”. It extends the C language with features for data abstraction, extended facilities for user-defined types, a more extensive standard library, and improved safety, while still maintaining an emphasis on efficient runtime performance. The fact that C++ is a superset of C can be both a blessing (code compatibility) and a curse (unsafe features still exist). We switched our CS106B and X courses to C++ in 2002 and by focusing on a carefully chosen subset of features, we've been able to capitalize on the useful new functionality C++ provides and move away from some of the more treacherous areas of C. Java is a product of the 90s and had a meteoric rise to popularity; some of it due to the Internet boom given Java was promoted for web development. Java takes much of its basic language syntax and features from C and C++. However, philosophically, Java strikes out into new territory. It is fundamentally object-oriented, cross-platform compatible, and has a huge standard library. Java strongly values safety over efficiency and provides garbage-collection, array bounds-checking, checked typecasts, and more. Java compilers are much more strict than C/C++ and close the runtime safety loopholes present in C and C++. Java's combination of features makes it a good fit with an intro course and we switched our CS106A course to Java in 2004. All three of C, C++, and Java are widely used in industry and academia. We think it is valuable that you are learning tools that you will continue using in upper-division classes and summer internships and jobs. However, we also believe the programming skills we teach are not tied to the language. By exposing you to two languages across the intro sequence (and a few others in CS107) we're hoping to give you a solid foundation that transcends any one language or paradigm.
What does C++ look like? To start with, here is a complete C++ program that reads some numbers from the user and computes their average. */
both object-oriented and procedural features. C++ is termed a hybrid language, since it combines more than one paradigm. In this course, our approach to C++ is one that I call "procedural programming using objects". Much of our code will be written in the procedural style, in the form of global functions that operate sequentially but that code will use many objects (e.g. the standard string and stream classes, as well as our own library classes). For the first half of the quarter, we will not be defining any new classes at all. In the second half we will work on class implementation. Filename extensions Whereas Java source files are named with a .java extension (e.g. Binky.java ), our C++ source files are named with a .cpp extension (e.g. boggle.cpp ). Other conventions for C++ source file extensions include .C, .cc, and .cxx. #include (Reader page 1-5) In a C++ program, you must inform the compiler about features you are using from outside this file. This is done with #include statements at the top of the file, such as #include
Here is a program showing main and two other functions. void Binky(int num) { for (int i = 0; i < num; i++) cout << "Hello!" << endl; } int Winky() { cout << "Enter your favorite number: "; return GetInteger(); } int main() { // execution starts here int val = Winky(); Binky(val); return 0; // and stops here } A few things to note
on). The restriction on what constitutes a valid integer reference makes sense if you think about it. For example, consider this call: Adjust(3+5, 45);* Although it is fine to pass an expression for the second argument, there is no sensible interpretation for using an arithmetic expression as a reference for the first argument, thus this call produces is a compile error. A classic use of pass-by-reference is shown by this Swap function to exchange two values: void Swap(double & a, double & b) // a, b are ref params { double tmp = a; a = b; b = tmp; } When you call this function, you pass two variables to exchange: double x = 1, y = 3.4; Swap(x, y); And after the function executes, x will have the value 3.4 and y 1. You cannot write such a Swap function in Java because of its lack of reference parameters! Even when the called function does not modify the parameter, a C++ programmer will often mark any struct or object parameter as pass-by-reference. These items can be often large in size and using pass-by-reference avoids the inefficiency of making copies of these large items as they are passed around. As a habit, we will typically pass objects by reference for this reason of efficiency. Constants (Reader pages 1-5 to 1-6) The const type modifier is used when defining named constants. A constant is like declaring a variable with a name and a type, and includes an initializer to set the value. const int MaxEntries = 100; The const modifier assures that once assigned, the value will not change; any attempt to modify a constant will result in a compiler error. Constants allow you to associate a name with a value and then use the name in place of the value for purposes of readability and code maintenance. These are like the static final fields you used as constants in Java. By convention, C++ constants are often named in uppercase. const double PI = 3.141519; const double TWO_PI = (PI2);* Constants are usually listed at the top of the file, after the #include statements. These statements are defined outside any class context. Similar to functions they exist globally— these constants are accessible anywhere within the file once they have been defined. The C++ const modifier has many other uses (parameters, member functions, etc.) but managing those details is a topic we defer to CS107. In our course, we use const only for program-level constants.
enum (Reader section 2.1) The enum keyword is used to introduce a new type with a limited set of named values. For example, the declaration below creates a new type for day of the week: enum weekdayT {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; This declaration creates weekdayT as an enumerated type, with possible values ranging from Sun to Sat. The type weekdayT can be used for variables, parameters, return types, and so on. weekdayT day; day = Sun; if (day == Mon) ... Behind the scenes, weekdayT is just a special kind of integer and each name is mapped to a value ( Sun is 0, Mon is 1, etc.) but using an enumerated type is less error-prone and more self- documenting than that using integers with defined constants. struct (Reader section 2.6) The struct keyword is used to define a new type that is a collection of fields in one package. Structures are used to group logically related data into one variable. For example, an inventory program might track an item using a struct containing the name, price, and stock status: struct itemT { string name; double price; bool inStock; }; This type declaration establishes itemT as a new record type containing three fields. This type can be used for variables, parameters, return types, and so on. itemT it; it.name = "Hula hoop"; it.price = 25.99; it.inStock = true; The fields within a struct are accessed using dot notation. This notation should be familiar to you from Java, which uses dot notation to access fields within an object. In fact, a struct is like an object, where the fields are public to everyone and there are no methods to operate on it. Structs are most appropriate when the data being managed has no behavior and there is no need for encapsulation. Pointers (Reader section 2.3) A pointer is just a special type of variable that stores a memory address. That address allows you to access some other piece of data, called the pointee. You can then access the data to read and write by reference through the pointer. Pointers are one of the trickier features of C++. Even though Java doesn't let you explicitly manipulate pointers, there are there just the same, so you have more experience with pointers than you might think! In Java, all array and object variables are pointers, even though the syntax doesn't make this apparent. When a Java program declares an array or object, space is allocated only for the pointer. You must assign that pointer to hold the location of an object in the heap in order to use it.
As a minor complication, there are two variants of delete , one with brackets and one without. The special form delete[] is used to deallocate an array that was earlier allocated using new[] (i.e an entire array allocated such as new int[num] ). The basic rule is that every new call should be balanced by exactly one delete call and similarly each new[] call is matched by a delete[] call. Figuring out what and when to delete can be a difficult task, and getting it wrong can have disastrous consequences. Typically you write the program first with no attempt to clean up memory and then slowly and carefully add the necessary delete statements to clean up where appropriate. Arrays (Reader section 2.4) Java arrays and C++ arrays have fairly similar syntax, but operate somewhat differently underneath. Below shows some C++ code for allocating and manipulating some arrays: *int arrOnStack[50]; int arrInHeap; arrInHeap = new int[50]; for (int i = 0; i < 50; i++) { arrOnStack[i] = i; arrInHeap[i] = arrOnStack[i] * 2; } delete[] arrInHeap; Some things to note:
Here's a simple Location class for an x,y coordinate pair. It has two data members, a constructor, and three member functions: two accessors and one modifier. Here is the class declaration in location.h (by convention, the name of the file is lowercase): class Location { public: Location(int xVal, int yVal); // ctor like Java int getX(); int getY(); void translate(int dx, int dy); private: int x, y; }; // this ending semicolon is important! A couple of things to point out right away:
Strings (Reader section 3.3) Just as in Java, there is a standard C++ class for managing a sequence of characters. The C + + string class is quite similar to Java's String class. Consider the C++ code below: string s = "apple"; string t = "banana"; for (int i = 0; i < s.length(); i++) cout << s[i]; // square brackets to access chars t = s.substr(0, 3); // creates new substring t[0] = 'm'; // C++ strings are mutable! s = t + "binky"; // concat works for strings & chars if ( s == "Stanford") s += "!"; int index = s.find("an"); A few things to note:
To read from a C++ stream, you can use the extraction operation >>. The console input stream is named cin. For example, the following code reads two integers from the console: int x, y; cin >> x >> y; (I know << and >> can be easily confused. Here's a way to help keep it straight: The stream is always on the far left and the arrows point in the direction of the information flow. If printing information out to the stream, the arrows point from the variables to the stream. If reading information in from the stream, the arrows point from the stream to the variables). We will avoid using raw stream extraction on the console because it's tedious to handle the inevitable user typing errors (such as entering a letter when a number was expected). Instead, use our convenience functions in simpio.h that handle these details. For example, the code below shows a typical way to interact with the user at the console: cout << "What is your name?"; string name = GetLine(); cout << "How old are you?"; int age = GetInteger(); cout << "How much would you pay for this fabulous course?"; double price = GetReal(); Reading and writing to files (as opposed to the console) uses the same basic approach. You use the classes ifstream and ofstream (input and output file streams) and the same insertion and extraction operators. There are also facilities for reading char-by-char and line-by-line. Here is some sample code that copies one file to another one line at a time: #include