PEG:C++ Lesson 2 for Pascal Users

From PEGWiki
Jump to: navigation, search
← Previous Lesson | Next Lesson →

This lesson is brief and discusses the basic "mechanics" of C++. It's not going to teach you to code anything, but you need to know this anyway (some of you might have guessed by yourselves).

C++ code consists of a sequence of statements to be evaluated one after another. For now all your programs will execute statements one-by-one from top to bottom between the opening brace { and the closing brace } following int main(). These are like the begin and end reserved words in Pascal. The last line of code, the final statement, should read return 0;. (This is not strictly necessary; the program will work without it. However, in larger and more complicated programs, it tells anyone reading the code that execution stops once it reaches that line.) All simple statements in C++ end with semicolons, just like in Pascal. (But in C++, even the final statement before } needs a semicolon. In C++, semicolons are statement terminators, unlike in Pascal, in which they are statement separators.)

That code above int main() --- the #include <iostream> and using namespace std; --- those lines should remain in all C++ programs you write, for the time being. We will explain at a later time what they really mean. For now, think of them as being like uses crt;; they do not perform exactly the same function, but it's the same general idea. You need #include <iostream> in order to perform C++-style input/output.

You may have noticed that the code following // was colored green when you pasted the previous lesson into Visual C++. In general, anything on a line following // is treated as a comment, but once you get to the next line it's not a comment anymore. There are also Pascal-style comments, which are also in green: /* starts a comment and */ ends it, just like { and } in Pascal (these comments can span multiple lines.)

Execution of C++ code can be considered to progress generally toward evaluation, with everything else merely a side effect. Thus, statements like 3+5; are perfectly legal in C++; they can be evaluated, and the fact that they don't actually do anything is irrelevant. The statement cout << "Hello Fox" << endl; has a value too; explaining what this value is and how it is obtained will come later on. Even though this statement's purpose is to perform an action --- printing text to standard output --- the compiler sees it as a request to evaluate the statement, incidentally performing a sequence of steps along the way that happen to print out the text.