Chapter 2 - Hello World!

Review

1. What is the purpose of the “Hello, World!” program?

To check your program environment and to get acquainted with the tools and to see if everything is setup correctly. Its purpose is to get us acquainted with the basic tools of programming. It is here to learn the basics of a programming tool. This helps later on the be not distracted when learning more complex language constructs.

2. Name the four parts of a function.

  • A return type, here int (meaning “integer”), which specifies what kind of result, if any, the function will return to whoever asked for it to be executed. The word int is a reserved word in C++ (a keyword), so int cannot be used as the name of anything else (see §A.3.1).
  • A name, here main.
  • A parameter list enclosed in parentheses (see §8.2 and §8.6), here (); in this case, the parameter list is empty.
  • A function body enclosed in a set of “curly braces,” { }, which lists the actions (called statements) that the function is to perform.
int main()
{
    // statements
}

3. Name a function that must appear in every C++ program.

Every C++ program must have a function called main to tell it where to start executing.

4. In the “Hello, World!” program, what is the purpose of the line return 0;?

main() is called by “the system,” we won’t use that return value. However, on some systems (notably Unix/Linux) it can be used to check whether the program succeeded. A zero (0) returned by main() indicates that the program terminated successfully.

5. What is the purpose of the compiler?

C++ is a compiled language. That means that to get a program to run, you must first translate it from the human-readable form to something a machine can “understand”. That translation is done by a program called a compiler. What you read and write is called source code or program text, and what the computer executes is called executable, object code, or machine code. Typically C++ source code files are given the suffix .cpp (e.g., hello_world.cpp) or .h (as in std_lib_facilities.h), and object code files are given the suffix .obj (on Windows) or .o (Unix).

The compiler reads your source code and tries to make sense of what you wrote. It looks to see if your program is grammatically correct, if every word has a defined meaning, and if there is anything obviously wrong that can be detected without trying to actually execute the program.

6. What is the purpose of the #include directive?

It instructs the computer to make available (“to include”) facilities from a file (header) that is followed by the #include directive. Header includes are either enclosed in a pair of ” if they are local header files relative to the file they are included to or in opening and closing angle braces < > if the headers are globally available to the project such as the standard includes.

7. What does a .h suffix at the end of a file name signify in C++?

A file included using #include usually has the suffix .h and is called a header or a header file. A header contains definitions of terms, such as cout, that we use in our program.

8. What does the linker do for your program?

A program usually consists of several separate parts, often developed by different people. For example, the “Hello, World!” program consists of the part we wrote plus parts of the C++ standard library. These separate parts (sometimes called translation units) must be compiled and the resulting object code files must be linked together to form an executable program. The program that links such parts together is (unsurprisingly) called a linker.

Please note that object code and executables are not portable among systems. For example, when you compile for a Windows machine, you get object code for Windows that will not run on a Linux machine.

9. What is the difference between a source file and an object file?

What you read and write is called source code or program text, and what the computer executes is called executable, object code, or machine code. Typically C++ source code files are given the suffix .cpp (e.g., hello_world.cpp) or .h (as in std_lib_facilities.h), and object code files are given the suffix .obj (on Windows) or .o (Unix). Object code files are generate by the compiler while source code files are generated by the programmer or can be generated automatically using tools.

10. What is an IDE and what does it do for you?

To program, we use a programming language. We also use a compiler to translate our source code into object code and a linker to link our object code into an executable program. In addition, we use some program to enter our source code text into the computer and to edit it. These are just the first and most crucial tools that constitute our programmer’s tool set or “program development environment.”

An IDE (“interactive development environment” or “integrated development environment”) usually includes an editor with helpful features like color coding to help distinguish between comments, keywords, and other parts of your program source code, plus other facilities to help you debug your code, compile it, and run it.

11. If you understand everything in the textbook, why is it necessary to practice?

The purpose of a drill is to establish or reinforce your practical programming skills and give you experience with programming environment tools. A traditional set of exercises is designed to test your initiative, cleverness, or inventiveness.

Repetition and practice are necessary to develop programming skills. In this regard, programming is like athletics, music, dance, or any skill-based craft. Imagine people trying to compete in any of those fields without regular practice. You know how well they would perform. Constant practice — for professionals that means lifelong constant practice — is the only way to develop and maintain a high-level practical skill.

Terms

//

Anything written after the token // (that’s the character /, called “slash,” twice) on a line is a comment. Comments are ignored by the compiler and written for the benefit of programmers who read the code. Double forward slashes are used for comments. Comments are meant to explain the source code to other programmers and yourself after a long not reading it for a long time.

// output “Hello, World!”

<<

Is the output operator and is used to output strings or characters to the standard output using cout.

cout << "Hello, World!\n"; // output “Hello, World!”

It can also be used to shift bits.

C++

Is a programming language TODO

comment

Comments are written to describe what the program is intended to do and in general to provide information useful for humans that can’t be directly ex- pressed in code. The person most likely to benefit from the comments in your code is you — when you come back to that code next week, or next year, and have forgotten exactly why you wrote the code the way you did. Used to explain the source code to other programmers and yourself after not reading it for a long time.

compiler

C++ is a compiled language. That means that to get a program to run, you must first translate it from the human-readable form to something a machine can “understand.” That translation is done by a program called a compiler. What you read and write is called source code or program text, and what the computer executes is called executable, object code, or machine code. Typically C++ source code files are given the suffix .cpp (e.g., hello_world.cpp) or .h (as in std_lib_facilities.h), and object code files are given the suffix .obj (on Windows) or .o (Unix).

The compiler reads your source code and tries to make sense of what you wrote. It looks to see if your program is grammatically correct, if every word has a defined meaning, and if there is anything obviously wrong that can be detected without trying to actually execute the program. A program that checks the syntax of a source code and translates it to object code.

compile-time

Errors found by the compiler are called compile-time errors, errors found by the linker are called link-time errors, and errors not found until the program is run are called run-time errors or logic errors. Generally, compile-time errors are easier to un- derstand and fix than link-time errors, and link-time errors are often easier to find and fix than run-time errors and logic errors. The time the compiler is analyzing the source code and translating it to object code. At this state compile-time errors are captured.

error

Errors can be categorized into compile-time (missing include or syntax errors such wrong spelling of standard types or missing semicolons), link-time errors (used declarations but without finding the definitions) and runtime or logical-errors (accessing null pointers or memory addresses that was already deleted, stack variables passed as references).

cout

The name cout refers to a standard output stream. Characters “put into cout” using the output operator << will appear on the screen. The name cout is pronounced “see-out” and is an abbreviation of “character output stream. Function in the standard iostream header to write strings and characters to the standard output stream.

executable

What the computer executes is called executable, object code, or machine code. Typically C++ object code files are given the suffix .obj (on Windows) or .o (Unix). A program or an application that is the final result of compiling source files to object files and linking them to an executable that can be executed.

function

A function is basically a named sequence of instructions for the computer to execute in the order in which they are written. A function has four parts:

  • A return type, here int (meaning “integer”), which specifies what kind of result, if any, the function will return to whoever asked for it to be exe- cuted. The word int is a reserved word in C++ (a keyword), so int cannot be used as the name of anything else (see §A.3.1).
  • A name, here main.
  • A parameter list enclosed in parentheses (see §8.2 and §8.6), here (); in this case, the parameter list is empty.
  • A function body enclosed in a set of “curly braces,” { }, which lists the actions (called statements) that the function is to perform.
int main()
{
    // statements
}

A piece of source code that encapsulates statements inside curyly braces that are executed in order. A function can have a parameter list and has a return type which can be void.

IDE

IDE (“interactive development environment” or “integrated development environment”) usually include an editor with helpful features like color coding to help distinguish between comments, keywords, and other parts of your program source code, plus other facilities to help you debug your code, compile it, and run it. To program, we use a programming language. We also use a compiler to translate our source code into object code and a linker to link our object code into an executable program. In addition, we use some program to enter our source code text into the computer and to edit it. Inegrated or Interactive Development Envornment is a tool with helpful features for creating new programs.

#include

An “#include directive.” instructs the computer to make available (“to include”) facilities from a file. A preprocessor directive to include a header file that can contain required definitions for example from the standard library.

#include "std_lib_facilities.h" // facilities from a header file locally available within a file relative to the current file.
#include <vector> // facility from the standard library ("globally" available)

library

A library is simply some code — usually written by others — that we access using declarations found in an #included file. A declaration is a program statement specifying how a piece of code can be used. A collection of facilities (such as functions or classes) that can be reused and make it easier to create new applications.

linker

A program usually consists of several separate parts, often developed by different people. For example, the “Hello, World!” program consists of the part we wrote plus parts of the C++ standard library. These separate parts (sometimes called translation units) must be compiled and the resulting object code files must be linked together to form an executable program. The program that links such parts to- gether is (unsurprisingly) called a linker. One program in the build process that links one ore more object files together to create an executable.

main()

The main entry point of every C++ program. It returns an integer denoting the success of the program and can have command line arguments as its input parameters.

object code

A file with ending .obj on Windows and .o on Linux which contains object code. Is created invoking the compiler on a source code file (.h or .cpp).

output

For example the text a program outpus using cout.

program

An executable program or application that is the result of compiling source codes files to object files and linking them to an executable program.

source code

Instructions of a program that are written in a text editor inside a header (.h) or source code file (.cpp).

statement

A line of source code that is terminated by a semicolon inside a block of curly braces for example of a function.

Exercises

  1. Change the program to output the two lines Hello, programming! Here we go!
  2. Expanding on what you have learned, write a program that lists the instructions for a computer to find the upstairs bathroom, discussed in §2.1. Can you think of any more steps that a person would assume, but that a computer would not? Add them to your list. This is a good start in “thinking like a computer.” Warning: For most people, “go to the bathroom” is a perfectly adequate instruction. For someone with no experience with houses or bathrooms (imagine a stone-age person, somehow transported into your dining room) the list of necessary instructions could be very long. Please don’t use more than a page. For the benefit of the reader, you may add a short description of the layout of the house you are imagining.
  3. Write a description of how to get from the front door of your dorm room, apartment, house, whatever, to the door of your classroom (assuming you are attending some school; if you are not, pick another target). Have a friend try to follow the instructions and annotate them with improvements as he or she goes along. To keep friends, it may be a good idea to “field test” those instructions before giving them to a friend.
  4. Find a good cookbook. Read the instructions for baking blueberry muffins (if you are in a country where “blueberry muffins” is a strange, exotic dish, use a more familiar dish instead). Please note that with a bit of help and instruction, most of the people in the world can bake delicious blueberry muffins. It is not considered advanced or difficult fine cooking. However, for the author, few exercises in this book are as difficult as this one. It is amazing what you can do with a bit of practice.
  • Rewrite those instructions so that each individual action is in its own numbered paragraph. Be careful to list all ingredients and all kitchen utensils used at each step. Be careful about crucial details, such as the desired oven temperature, preheating the oven, the preparation of the muffin pan, the way to time the cooking, and the need to protect your hands when removing the muffins from the oven.
  • Consider those instructions from the point of view of a cooking nov- ice (if you are not one, get help from a friend who does not know how to cook). Fill in the steps that the book’s author (almost certainly an experienced cook) left out for being obvious.
  • Build a glossary of terms used. (What’s a muffin pan? What does preheating do? What do you mean by “oven”?)
  • Now bake some muffins and enjoy your results.
  1. Write a definition for each of the terms from “Terms.” First try to see if you can do it without looking at the chapter (not likely), then look through the chapter to find definitions. You might find the difference between your first attempt and the book’s version interesting. You might consult some suitable online glossary, such as www.stroustrup.com/glossary.html. By writing your own definition before looking it up, you reinforce the learning you achieved through your reading. If you have to reread a section to form a definition, that just helps you to understand. Feel free to use your own words for the definitions, and make the definitions as detailed as you think reasonable. Often, an example after the main definition will be helpful. You may like to store the definitions in a file so that you can add to them from the “Terms” sections of later chapters.
helloworldextended.cpp
1
2
3
4
5
6
7
8
9
#include "std_lib_facilities.h"

int main() // C++ programs start by executing the function main
{
    cout << "Hello, programming!\n"; // output “Hello, World!”
    cout << "Here we go!\n"; // output “Hello, World!”
    keep_window_open(); // wait for a character to be entered
    return 0;
}