C++
Introduction to C++
By Juan Felipe Martínez Bedoya
- Compiling and running
- Comments
- Variables
- Loops
- Operators
- Conditionals
- Functions
- Including external code
- Input and output
C++ is a compiled language: the code is translated into machine code before it runs, unlike interpreted languages (such as Python), which are translated as they run. This has two important consequences:
- After any change you must compile again before running.
- Compiled programs are usually much faster than interpreted ones.
Compiling and running
C++ files have the .cpp extension. They are compiled with g++:
g++ -std=c++17 name.cpp -o name_compiled
-std=c++17sets the version of the C++ standard.name.cppis the file being compiled.-o name_compiledis the name of the executable produced.
To run it:
./name_compiled
Comments
// Single-line comment
/* Comment
over several
lines */
Variables
A variable is declared as type name = value;. Its value can change, but its type cannot change while the program runs.
int number = 0;
int a; // you can also declare it without a value...
a = 0; // ...and assign it later
To create an object of a class and use its methods:
MyClass myObject;
myObject.method();
Numbers
int: whole numbers.float: decimal numbers.double: likefloat, but with more precision.bool: true (true) or false (false).
Strings
std::string stores text of any length. It is written in double quotes and requires <string>:
#include <string>
std::string greeting = "Hola";
A char array also stores text, but with a fixed length. It needs room for the final null character, so “Hola” needs 5 positions:
char greeting2[5] = "Hola";
In both cases each character is accessed by its index, from 0 to the length minus 1. Single characters go in single quotes:
char f = greeting[0]; // 'H'
char g = greeting[1]; // 'o'
To concatenate (join) strings, use +:
std::string name = "ARES";
std::string message = greeting + " " + name; // "Hola ARES"
Lists and vectors
std::vector is the most common structure for a sequence of elements that can grow. std::list also exists and makes adding elements at the front efficient.
#include <vector>
#include <list>
std::vector<int> v = {1, 2, 3};
v.push_back(4); // add at the end
std::list<int> list = {1, 2, 3};
list.push_front(0); // add at the front
list.push_back(4); // add at the end
To print their elements you have to loop over them (see below).
Dictionaries
In C++ they are called std::map. They store pairs of key and value. When creating one, give the key type first and then the value type:
#include <map>
std::map<std::string, int> dictionary;
dictionary["value 1"] = 1;
dictionary["value 2"] = 2;
Loops
Looping over a collection:
for (int val : list) {
// repeated code
}
Counting from x to y:
for (int i = x; i <= y; i++) {
// repeated code
}
Repeating while a condition holds:
while (condition) {
// repeated code
}
Operators
Arithmetic
+ addition, - subtraction, * multiplication, / division and % modulo (remainder). Note: dividing two int values gives an int (7 / 2 is 3).
Assignment
| Operator | Same as |
|---|---|
x = 2 |
stores 2 in x |
x += 2 |
x = x + 2 |
x -= 2 |
x = x - 2 |
x *= 2 |
x = x * 2 |
x /= 2 |
x = x / 2 |
x %= 2 |
x = x % 2 |
Comparison
They return true or false: == equal, != not equal, < less than, <= less than or equal, > greater than, >= greater than or equal.
Logical
They work on boolean values: && (and), || (or), ! (not).
Conditionals
if (x > 0) {
// ...
} else if (x == 0) {
// ...
} else {
// ...
}
Functions
A function is defined with the type it returns (int, float, bool, void if it returns nothing…), its name and its parameters, each with its type:
int add(int a, int b) {
return a + b;
}
Every program has a main function, where execution starts. It returns 0 if everything went well:
int main(int argc, char **argv) {
// ...
return 0;
}
Including external code
#include brings in libraries. Use quotes for your own files next to the code, and < > for system or external libraries:
#include "myClass.h" // your own file
#include <rclcpp/rclcpp.hpp> // external library (ROS 2)
.h (or .hpp) files are headers: they declare classes and functions, while their implementation goes in .cpp files.
Input and output
printf
#include <cstdio>
int a = 42;
printf("a is %i\n", a); // %i for integers
float b = 3.1415;
printf("b is %.2f\n", b); // %.2f: float with 2 decimals
std::string word = "Hey!";
printf("%s\n", word.c_str()); // %s for text; convert a string with c_str()
cout and cin
#include <iostream>
#include <string>
using namespace std; // lets you write cout instead of std::cout
int main() {
cout << "Hello world!" << endl; // endl ends the line
int x;
cout << "Enter a number: ";
cin >> x;
string name;
cout << "What is your name? ";
cin.ignore(); // discard the pending newline
getline(cin, name); // read the whole line, spaces included
cout << "Hello, " << name << endl;
return 0;
}
cin >> variable only reads up to the first space. To read a whole line, such as “Hello world”, use getline.
Translated from Spanish.