Chris Gregory

Home Blog LinkedIn Github

C++ Tutorial 1 - Introduction

12/19/2016

This series of tutorials is the general learning plan for C++. I presume you have Visual Studio installed. If you are working on Mac/Linux, use a text editor like Emacs and compile via the command line:

$ g++ -o OUTPUT_FILE INPUT_FILES -std=c++11 && ./OUTPUT_FILE

Make a project if using Visual Studio and open a file of the name first.cpp. This file will be INPUT_FILES for the command line compilers.

Hello world:

#include <iostream>
#include <cstdio>

using namespace std;

int main() {
    cout << "Hello World!\n";

    // If you are using Visual Studio, add the following line to keep
    // the terminal open until you input a key.
    getchar();

    return 0;
}

Try printing out your name by changing the text inside the double quotes to Czipperz or something of the like.

Try printing out a number, removing the quotes entirely doing so.

Let's look at the structure of our program. The first two lines tell the compiler to look up information related to input and output on the terminal with the user.

The third line tells the computer to use the standard library (std).

The fourth line tells the computer we are writing a function, one named main that will return an integer (int). Since there is nothing inside the parenthesis, the function takes no arguments from its caller. The open curly bracket ({) indicates a function body: the code that will run when the function is called. Running our program will automatically call main().

The fifth line instructs the computer to print the string "Hello World!\n" to the terminal. The "\n" instructs it to print a new line.

The sixth and optional line instructs the compiler to get a character from the user, keeping the program alive until so.

The seventh line instructs the compiler to signal successful completion of the program. Returning a non-zero number from main() signifies an error.

The eighth and final line closes the function and ends the program.