Posts Tagged ‘ Thinking in C++ ’

C++ Language Tutorial — Basics of C++: Structure of a Program

Initially, I looked at C++ Language Tutorial by Juan SouliƩ, but I found Thinking in C++ by Bruce Eckel recommended on the KDE development page, so I am going to read both.

At first glance, Eckel’s book looks like a really heavy read. If I may say so, it’s very… hard-core? Perhaps bleak? Okay, I may be biased toward pretty, colorful code blocks used in the C++ Language *Tutorial*, but really—Eckel’s first chapter is a slightly ominous, philosophical “Introduction to Objects.” The chapters are much more detailed than SouliĆ©’s tutorial (after all, it’s just that, a tutorial).

Hopefully, I’ll be able to pluck up some courage to read that chapter once I’ve learned a reasonable amount of syntax and structure. It seems like a great book, but it looks way too scary right now.

So getting started with the tutorial:

A basic C++ program as a model, copied from the site:

// my first program in C++

#include 
using namespace std;

int main () {
  cout << "Hello World!";
  return 0;
  }

All text after two slash signs (//) are comments. Block comments can be inserted between /* and */.

Lines beginning with a hash sign (#) are directives for the preprocessor. In this example, #include tells the preprocessor to include the iostream file, which is the basic input-output library in C++ (which defines cout).

“All the elements of the standard C++ library are declared within what is called a namespace… with the name std.” We call it with using namespace std, and it is frequently used in C++ programs that use the standard library.

int main () is the beginning of the definition of the main function, which is where all C++ programs start their execution. Other functions may be defined elsewhere and anywhere, but the main function will be executed first (thus is essential to every C++ program). The parentheses can optionally enclose a list of parameters. The body of the function is enclosed in a pair of braces.

A statement is an expression that can produce an effect. cout << "Hello World!"; outputs the string of characters Hello World! into the standard output (e.g., the screen). All expression statements are terminated by a semicolon.

The return statement in this example is followed by a return code of 0, which generally indicates a successful execution of the program. C++ console programs are usually ended in this way.

With the exception of lines of preprocessor directives (they are not statements), whitespace is insignificant. Semicolons are important.