C++ Notes
ToC
Basics
I. Introduction
A C++ program generally consists of preprocessor directives and the main function.
A preprocessor directive tells the C++ preprocessor what to do before compiling. You can use this to include files, create macros, and determine compiling based on conditions. For example, include a file using #include This will include the iostream file from the C++ standard library.
The main function looks like:
The int main() {
std::cout << "Hello world" << '\n';
return 0;
}int main() { is the declaration of the main function denoting it returns type int. return 0; is the return statement for the function. It is returning the integer 0. This tells the operating system, OK Quit the program safely.
II. Variables
A variable lets you allocate some memory in the computer and use it to store values. You can also recall the values for later. Variables contain a memory address and an identifier. An identifier can be *almost* anything you wish it to be.
Variables naming rules:
- Cannot start with a number.
- Can only contain alphanumeric characters and underscores.
- Cannot contain any reserved keywords (see here).
- If starting with an underscore, it can only start with one.
Variable types:
- Integers:
- short int:
- Size: 2 bytes.
- Range: -32,768 to 32,767
- int:
- Size: 4 bytes.
- Range: -2 billion to 2 billion
- short:
- Size: 8 bytes.
- Floats:
- float:
- Size: 4 bytes.
- 6 significant figures.
- double:
- Size: 8 bytes.
- 15 significant figures.
- long double:
- Size: 16 bytes.
- 19 significant figures.
- Character:
- Type: char Stores an integer value representative of an "ASCII" character.
- Size: 1 byte.
- String:
- Usage:
#include - Variable creation:
std::string identifier = "string literal"; - Boolean:
- Type: bool
- Size: 1 byte
-
Stores an indexable array of characters.
-
Stores an integer value of 0 or 1 representative of false or true respectively.
Variables are always declared before they are initialized. This means you must determine the type and the identifier before you store any values into it.
int main() {
int a; // Declaration
a = 1; // Initialization
int b = 2; // Declaration then initialization
}Constant types are variables identified by
const in their type definition. These are not allowed to be modified after they are declared and must be initialized at declaration.
III. Operators
Just like in mathematics, operators let you perform functions on elements. We'll start by viewing arithmetic operators and assignment.
The assignment operator, denoted by = allows you to assign values to a variable. Assigning a variable with a value of a different type will give you a warning. This can be solved by casting the value being assigned to the same type as your variable: static_cast. Assignment also works from right to left. Values on the right of the assignment operator get assigned to the identifier on the left of the assignment operator.
Arithmetic operators allow you to do operations such as addition, subtraction, multiplication, division, and remainder division.
When dividing with numbers, it is important to know the type of numbers you are dividing. Division between integers will only return a whole number. For example 5 / 2 = 2. Suppose the 5 was a floating point type then, 5.0 / 2 = 2.5. It is important to know what types you are using when performing division.
When wanting to perform division and only return the remainder, you can use the modulus operator. For example, 5 / 2 = 2 whereas 5 % 2 = 1. 2 is the quotient and 1 is the remainder.
- + Addition
- - Subtraction
- * Multiplication
- / Division
- % Modulus
-
Post increment/decrement:
This will return the current value and then perform the operation.
x++
x-- -
Pre increment/decrement:
This will perform the operation, then return the current value.
++x
--x x += yx -= yx *= yx /= yx %= y
The following is short for
x = x (operation) y:
Relational Operators
- Less than: <
- Greater than: >
- Less than or equal to: <=
- Greater than or equal to: >=
- Is equal to: ==
- Is not equal to: !=
- AND: &&
- OR: ||
- NOT: !
Operators with the same precedence are evaluated in the statement from left to right.
| 1st | Last | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| (a) | x++, x++ | ++x, --x | ! | * / % | + - | < > <= >= | == != | && | || | = |
Control Flow
I. Decision Branching
An if statement will execute instructions if the condition evaluates to true. You can remember this as if something is true, then my program will do this. For example:
will execute "1 is equal to 1".int main() {
int x = 1;
if (x == 1) {
std::cout << x << " is equal to 1.\n";
}
return 0;
}
An if-else statement will execute instructions if the condition is true and execute different instructions when the condition is false.
int main() {
int x = 1;
if (x == 1) {
std::cout << x << " is equal to 1.\n";
}
else {
std::cout << x << " is not equal to 1.\n";
}
return 0;
}
One thing to note about these types of control statements, is that they can be nested to create a decision branch. A branch, like of a tree, splits off into many smaller branches. The more nested if-else statements you have, the more and more branches you add to your decision tree.
II. Loops
Loops are good when you need to repeat a segment of instruction multiple times. There are a few different types of loops to be aware of.
- While loop
- Do-While loop
- For loop
int main() {
int x = true;
while (x == true) {
std::cout << "Hello!";
}
}This while loop will run infinitively many times because x will always equal true. There is no where in this program that the value of x changes so the loop will never leave the brackets of the while loop.
The do-while loop will always evaluate once. This is because, unlike the while loop, the condition is checked after the main body executes.
int main() {
int x = true;
do {
std::cout << "Hello!";
} while (x == false);
}Note the slight change to the condition. This loop will repeat when x is false though as you can see, x is initialized to be true. However, unlike the while loop previously, this will output just one "Hello". You can see that the condition is placed after the
do { .. } so the condition gets checked after it executes.The final type of loop is the for loop. This is used when the number of iterations of the loop is determine before the loop starts. You should not change the number of iterations after you create the loop.
int main() {
int x = true;
for (int i = 0; i < 10; i++) {
std::cout << "Hello!";
}
}You can see here, the for loop starts at
i = 0, checks if i < 10, then outputs Hello!. Then i++ executes and i increases by 1. Then the loop repeats. The loop checks if i < 10. i is 1 now so this is true and the program outputs Hello!. This repeats until i < 10 is false which is when i = 10. Pretty simple stuff.
Now suppose you want to leave a loop before the condition is false or skip an iteration quickly. Then you can use the break and continue statements. break will BREAK out of a loop causing is to cease executing. continue will SKIP everthing after the continue and start back at the top of the loop.
III. Switch
Suppose you have a large array of if-else statements.
Instead of writing that, you could've used a switch:if (a == 1) {
...
} else if (a == 2) {
...
} else if (a == 3) {
...
} else if (a == 4) {
...
} else if (a == 5) {
...
} else if (a == 6) {
...
} else if (a == 7) {
...
} else { ... }
switch (a) {
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
case 4:
...
break;
case 5:
...
break;
case 6:
...
break;
case 7:
...
break;
default:
...
break;
}
One caveat is that the case must be a literal value. It cannot be another value. Another is that a break; statement must be added to the end of every case or the statements will waterfall down from the case they started at to the next break statement. This is a feature of switches.
IV. Ternary Operator
The ternary operator lets you condense a simple if-else statement into one line.
This means that if a is greater than b, assign x with 1. If a is not greater than b, assign x with 0. The ternary operator however needs the values in the if and else part to be of the same type. If they are not, the program will fail to compile.
x = (a > b) ? 1 : 0;