DOC PREVIEW
Stanford CS 106B - CS106

This preview shows page 1-2-3-4-5 out of 14 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

CS106 Handout #4J Zelenski Jan 9, 2008Getting started in C++CS106B/X are taught using the C++ programming language, whereas our CS106A course usesJava. Becoming exposed to another language is an excellent way to broaden your experience whilesimultaneously 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 syntacticallysimilar 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 focusedon developing your "C++ legs". Although C++ is a complex and full-featured language, we willonly incorporate those features that fit well with our pedagogical course goals, so no need to worryabout having to learn an entire second language.This handout points out the Java/C++ differences most relevant to our course. These are just thehighlights and although we will skim these topics in lecture, plan on working through the first threechapters of the reader on your own to get the full story with additional in-depth examples.A little historyThe C programming language originated around 1970 and was designed for professionalprogrammers writing tight low-level code. The language is known for its terseness, limited supportlibraries, and runtime efficiency. It is known as an unsafe language because it makes tradeoffs thatvalue efficiency over safety (for example, access to array elements is not bounds-checked) and givesthe programmer unfettered access to do what they like (e.g. pointers and typecasts). C became quitepopular and even today is still one of the dominant languages in use. It is a good tool for anexperienced programmer, but not as appropriate for the rest of us mere mortals who could use somesafety goggles to go with our blowtorch.C++ arrives on the scene in the 80s designed as “a better C”. It extends the C language withfeatures for data abstraction, extended facilities for user-defined types, a more extensive standardlibrary, 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 (unsafefeatures still exist). We switched our CS106B and X courses to C++ in 2002 and by focusing on acarefully chosen subset of features, we've been able to capitalize on the useful new functionalityC++ 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 Internetboom given Java was promoted for web development. Java takes much of its basic language syntaxand features from C and C++. However, philosophically, Java strikes out into new territory. It isfundamentally object-oriented, cross-platform compatible, and has a huge standard library. Javastrongly 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 theruntime safety loopholes present in C and C++. Java's combination of features makes it a good fitwith 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 thatyou are learning tools that you will continue using in upper-division classes and summerinternships and jobs. However, we also believe the programming skills we teach are not tied to thelanguage. 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.2What does C++ look like?To start with, here is a complete C++ program that reads some numbers from the user andcomputes their average./* * average.cpp * ------------ * This program adds scores and prints their average. */#include "genlib.h"#include "simpio.h"#include <iostream>const int NumScores = 4;double GetScoresAndAverage(int numScores);int main(){ cout << "This program averages " << NumScores << " scores." << endl; double average = GetScoresAndAverage(NumScores); cout << "The average is " << average << "." << endl; return 0;}/* * Function: GetScoresAndAverage * Usage: avg = GetScoresAndAverage(10); * ------------------------------------- * This function prompts the user for a set of values and returns * the average. */double GetScoresAndAverage(int numScores){ int sum = 0; for (int i = 0; i < numScores; i++) { cout << "Next score? "; int nextScore = GetInteger(); sum += nextScore; } return double(sum)/numScores;}Familiar… but different, too.Things that are mostly the same between C++ and JavaA quick glance at the program above might mistake it for Java, so that gives you some idea howsimilar the basics are. In fact, enumerating all the features that are the same would be quite a longlist indeed! To give you an idea of some things you don't need to re-learn, consider these featuresshared by Java and C++:Both case-sensitiveSame use of punctuation (semicolons, curly braces, commas, parentheses, square brackets, … )Same comment sequence (/* comment */, // comment)3Same primitive variable types (e.g. int, double, char …)(although Java's boolean type is called bool in C++)Same operators for arithmetic, comparison, logical (e.g. +, %, *=, ++, ==, <, &&, ||,…)(same syntax, precedence, associativity, short-circuiting, conversions for mixed-types, etc.)Same control structures (e.g. if/else, for, while, switch, return, break …)All of the basic C++ language syntax is thoroughly covered in Chapter 1 of the reader. We highlyrecommend that you carefully read this chapter and work through some of the review questions andexercises to refresh your fundamental skills.Compiler/language strictnessBoth Java and C++ compilers are pretty assertive about making sure your code meets certainstandards (all variables declared, right number of parameters in calls, types used correctly, and soon) but there are some areas where a C++ compiler is noticeably lax compared to what you're usedto in Java. Some of this is historical accident (improved compilers make possible better


View Full Document

Stanford CS 106B - CS106

Download CS106
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view CS106 and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view CS106 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?