Language Overview: C++

This section provides a brief overview of C++.

The Main Function

A C++ program looks like the following:

#include <iostream>
using namespace std;

int main() {
	cout << "hello, world!" << endl;
	return 0;
}

All C++ progams must include the main() function. This is because the compiler must look for an entry point called main.

Comments

Comments in C++ can be either single- or multi-line:

// This is a single line comment

/*
 * This is a comment
 * that spans multiple
 * lines
 */

Include Statements

Because C++ code must be compiled before it can run, to use C++ code in a file other than the current source code file, we have to use an include statement. This is the only way we can notify the compiler that the code we write actually exists in some other file.

#include <iostream>
#include "myLibrary.h"

This is equivalent to the import statement in languages like Python and JavaScript. By C++ convention, the use of angle-brackets for include statements are reserved for the C++ standard library, and all other libraries should be imported with double quotes.

Console Output

To output data to the console, we can use the iostream library.

#include <iostream>

int main() {
	std::cout << "hello, world!" << std::endl;
	return 0;
}

std::cout will output hello, world to the console, and std::endl ends it with a new line.

Throwing Exceptions

To throw an exception in C++, we use the <stdexcept> library. For example:

#include <stdexcept>

void insert(int element, size_t position) {
	if (position > length) {
		throw std::invalid_argument("Invalid position argument");
	}
}