Video Coming Soon...

Created by Zed A. Shaw Updated 2024-11-15 13:50:32

02: A Simple First Program

Now that you have a functioning computer we can start to learn C++. To get things off the ground I'll have you create a file named ex02.cpp and enter this code into it:

View Source file ex02.cpp Only

#include <iostream>

using namespace std;

int main() {
  cout << "We'll have cake, in the end." << endl;

  return 0;
}

You should confirm that your code is exactly the same. Every space, character, and capitalization matters. Once you have it entered into your file you should save it. Actually, you should be hitting the save key constantly to make sure it's always saved.

About Terminal and shells

Before we get to the actual things you type I should cover a few more important pieces of information regarding the Terminal and "shell" programs.

Your Terminal program is named Terminal on both Windows and OSX. Windows also has the older version named cmd.exe and PowerShell. On Linux this program is probably also called Terminal but I'll leave it to you to figure that out. You're a Linux user now, good luck.

A "shell" is a program that runs inside Terminal and gives you textual access to your computer through commands. On OSX the shell used is can be bash or zsh depending on when you bought it. On Windows the shell is (confusingly) named PowerShell which also runs in Windows' Terminal or PowerShell window.

The easiest way to build and run your programs at this point is to use Terminal to enter commands telling the computer how to build it. However, when you see "shell sessions" in the book, they'll look like this:

$ echo "Hello From Shell"

If you start your Terminal and type this in it will probably not work because I'm adding a $ at the beginning that you should not type. The reason this is or a > character is frequently included in shell instructions is because we're trying to mimic the way your shell session looks. To make this command work you should only type echo Hello From Shell and it will look like this:

echo "Hello From Shell"

You'll see where you entered the command (called the "prompt") and then under that is the response Hello From Shell. All interactive sessions work this way.

Finally, you can usually press your up-arrow and down-arrow keys to go back through your history in case you want to rerun a command or find a past command you typed.

About Compilers

With your code entered into ex02.cpp you now need to compile it into a program you can run. C++ and many other languages use another program to translate the text you wrote to something called "machine code" or "byte code."

The compiler you will use should be named c++ and you run it from the Terminal like this:

c++ <input files> -o <output program>

When you read instructions like this you don't literally type the <input file> and <output program>. Those are simply "placeholders" for where you place the name of your .cpp files and the name of the program you want c++ to create. In our current example, you would actually type this:

c++ ex02.cpp -o ex02

In this example, you replaced <input files> with ex02.cpp and <output program> with ex02.

What You Should See

Now you're ready to finally compile your first program. Here's what you should do:

  1. Start your Terminal program.
  2. Type each line of the below session, but remember you don't type the $ character, only the text after. That's the output you should see.
  3. Keep this window open because you'll use it a lot.
$ c++ ex02.cpp -o ex02
$ ./ex02
We'll have cake, in the end.

If you typed your code correctly you should see exactly the same thing as what I have here (except maybe your prompt character is > or longer than mine).

Typing Code Effectively

If you wrote all the code correctly and didn't any errors, then awesome. However, if you didn't write the code correctly then that's even more awesome because you now get to practice writing code effectively. In fact, if you got lucky on your first try and had no errors I want you to delete your file and do it again. This will help you immensely.

The mistake most people make when writing code is they start at the top, type everything in, save once, and run it once. They then get tons of errors that are difficult to fix since it's not clear where many of the errors are located (more on that later).

A better way to enter in code--and the way I actually use even today--is to enter code in the smallest chunks that will work and constantly compile and run your code. You should be compiling and running your code at least 1-2 times for every 1 edit you make. Here's a general process you should follow from now on when typing your code:

  1. Enter 1 or 2 lines that will compile.
  2. Save your file.
  3. Run your compile command (remember up-arrow will recall your previous Terminal commands).
  4. Fix any errors, and keep running your compile while you do.
  5. Once the new code is working, go back to #1 and continue writing.

There's one tiny piece of information you need to make this work, and that has to do with the { (left-curly-brace) and } (right-curly-brace). If you see these you should enter them first, but empty, then fill them with contents. In the ex02.cpp file I might have the first 2 lines entered, and then do this:

int main() {
}

I call this the "taco method." You create the "shell" of the code, then fill it with contents, just like a taco.

Fixing Errors

If you get an error the compiler will tell you where it thinks you made a mistake. I will warn you right now, compiler error messages are some of the worst writing in all of human history. Yes, even worse than Game of Thrones fanfic. They're typically misleading and frequently point at the wrong line of code. Compiler error messages are also written in a weird style that only the compiler authors understand.

This means you'll have to work many times to decipher these error messages, so it's good to get practice now. First, here's an error I get if I delete the very first # character of ex02.cpp:

ex02.cpp:1:10: error: use of undeclared identifier 'iostream'
include <iostream>
         ^
ex02.cpp:3:1: error: expected unqualified-id
using namespace std;
^
ex02.cpp:6:3: error: use of undeclared identifier 'cout'
  cout << "We'll have cake, in the end." << endl;
  ^
ex02.cpp:6:45: error: use of undeclared identifier 'endl'
  cout << "We'll have cake, in the end." << endl;
                                            ^
4 errors generated.

You'll notice this is 4 errors even though I only broke one line. How you read this is:

  1. ex02.cpp -- This is the file where the error is located.
  2. 1 -- This is the line number that maybe has the error. Yes, it maybe has the error.
  3. 10 -- This is the character position where the error happened on that line. This is generally mostly useless.

I say that this is where the error might be because the compiler will often give you an error line, but actually the error is before that. To solve an error do this:

  1. Find the file:line that the compiler says has an error.
  2. Compare your line to mine and see what's different. If it's your own code then try to figure out what could be the error.
  3. If you can't find any errors, then check each line above that line as the error may have been triggered by a mistake before that line, but only caught by the compiler at this line.

Code Breakdown

Now that you have working code, and you've entered the code using the method I described, we can break the code down line by line so you understand what it's doing. Keep in mind C++ is an advanced language used by ancient programmers, so some of my explanation at this point is vague. It'll get clearer later as you progress through the course.

  1. #include <iostream> -- This tells c++ to include another file named "iostream" which gives your program the ability to read and write to the "input output stream." That's basically your terminal and keyboard.
  2. using namespace std; -- This says you want to default to using all the features found in the std namespace directly. A namespace is simply a way to categorize related features, and iostream includes many things in this. Doing this makes it easier to write code later.
  3. int main() { -- This is actually three separate things, but for now it's telling c++ where to start the program. When you run ex02 it jumps to this point in your code, then goes inside the { and runs everything you have there. Let's break down each part of this line:
    • int -- This is the used as an error code when your program exits.
    • main() -- This is the function that your computer knows is where your program starts.
    • { -- This starts the block of code that will actually be run.
  4. cout << "We'll have cake, in the end." << endl; -- This tells c++ to output the sentence "We'll have cake, in the end." to your Terminal screen. We should break this line down as well:
    • cout -- This is the output "stream" for your Terminal.
    • << -- This is how you "send" something to a stream. Put what you want to send after this.
    • "We'll have cake, in the end." -- This is a string. A string is a block of text that is not code, but usually a message or something you want to display to a user, save to a file, or send over a network. Think of it as "data not code."
    • << -- This is how you send more to the output stream.
    • endl -- This is a special "marker" that will output a line ending.
  5. return 0; -- This will exit your program and return to you shell the status code 0. Shells use this status code to determine if there was an error, with 0 being no error and any other number being a code for what error happened.
  6. } -- This ends your int main() { function and closes off the code that will be run. When the program hits this line it is done.

Keep in mind that you aren't expected to understand any of this completely. It will be a while before most of this makes sense, so you should take notes, and move on to the next lessons so you can keep practicing and studying until you understand it. It has to be this way because you don't know enough about programming to understand what I have to tell you to explain even this tiny little program. If you keep working through the course, this will eventually "click" and you'll get it. I promise.

Further Study

At the end of most exercises you'll be given a series of challenges to attempt to further your understanding. Most of these don't have "answers" and are simply things for you to try or figure out on your own. If you can't figure them out, then simply skip them and come back later to see if more knowledge helps you solve them.

  1. Break your code in more ways to see what errors the compiler gives you. You can usually just delete random characters to see what happens, but also try remove whole lines.
  2. Make your code say more things. Based on what you know, can you change what I wrote? Can you add more lines?
  3. ADVANCED How would you output a number?
Previous Lesson Next Lesson

Register for Learn C++ the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.