Lecture 01: C++ Basics

Jan 10, 2024  │  Last updated Jan 7, 2024 by Charlotte Curtis

HTML Slides html │ PDF Slides PDF

Where we left off

  • Course outline, policies, etc
  • Hello world
  • Tracing without explanation
  • Git + CLI adventures
int main() {
    int x = 0;
    int z = 0;
    while (x < 5) {
        z += x * x;
        ++x;
    }
    cout << z << '\n';
    return 0;
}

Today’s topics

Textbook Sections 1.3, 2.1-2.3

A C++ Program

Every C++ program has exactly one “main” function

int main() {
    // execution begins here
    ...
    return 0; // ends here
}

Unlike Python, C++ will not run without a main function!

Python vs C++

def main() -> None:
    print("Hello World!")
int main() {
    cout << "Hello World!\n";
    return 0;
}

Key points:

emoji Recall: statements vs expressions

Which of the following are true about statements? Select all that apply.

  1. Can contain expressions.
  2. Are instructions to the computer to do something.
  3. Can be assigned to a variable.
  4. Can include function calls
  5. Can be nested.

emoji Recall: statements vs expressions

Which of the following are true about expressions? Select all that apply.

  1. Can contain expressions.
  2. Are instructions to the computer to do something.
  3. Can be assigned to a variable.
  4. Can include function calls
  5. Can be nested.

Compiling vs Interpreting

The g++ Compiler

center height:150px

Recall: error types

Syntax, runtime, and logic errors

def abs_val(some_var: int) -> int:
    if some_var < 0:
        soem_var = 0

    return some_var
int abs_val(int some_var) {
    if (some_var < 0) {
        soem_var = 0;
    }

    return some_var;
}

The compiler is your friend! Compile-time errors are the easiest to fix.

Simple Output

Then we can use cout to print to the terminal

cout << "Hello World!\n";

Note that C++ does not include a newline by default

Side Tangent: Preprocessor directives and namespaces

Preprocessor directives are not statements, and do not end with a semicolon!

Variables and Types

At a high level, variables in C++ and Python are similar.

Python

x = 5    # int
x = "Meep" # str

C++

int x = 5;
x = "Meep"; // error!

Variable definition in Python

Internally, there’s a whole Rube Goldberg-esque process happening when you write x = 5 in Python. You end up with:

Python’s ease of use means a lot is hidden from the programmer!

Variable declaration and initialization in C++

It looks similar to Python, but we need to be explicit about the type:

int x = 5;
x = "Hello world!"; // error, x can only be an int!

Declaration and initialization can also be separated

int x; // declaration
x = 5; // initialization
int x; // error! We already declared that x was an int

Beware the uninitialized variable!

Separate or combined?

Variable naming

More or less the same restrictions as Python:

Convention is either snake_case or camelCase, just be consistent

Primitive Data Types

PythonC++Size
intint4 bytes
floatdouble8 bytes
boolbool1 byte
Nonevoid,NULL (ish)
str
char1 byte

str vs char

We’ll talk about strings more depth later, for now we’ll stick to string literals

emoji What do you think will happen?

This code compiles and runs. Predict the output from the choices below:

  1. 97
  2. aa
  3. 194
  4. 2a
  5. 2 * a
int main() {
    char a = 'a';
    cout << 2 * a << '\n';
    return 0;
}

The assignment operator

Much like in Python, the = operator assigns the value of the expression on the right hand side to the variable on the left hand side:

int x = 5;
int y = x + 1;
x = x - 1;
y = 5 / 2;

What’s going on with that 5 / 2?

Arithmetic operators

PythonC++Description
++Addition
--Subtraction
**Multiplication
//Division
///Integer division
%%Modulo (only for int)
**Exponentiation

Arithmetic with mixed data types

Practice!

For each of the following expressions, specify the data type of the result given i is an int and d is a double:

5 + i * 2 
d + i * 2
d / 9.33
7 / i
7.0 / i
42 + 7 / (i * 1.2)

In the end, the result is cast to the variable type, but there may be intermediate loss of precisions as in double y = 5 / 2

A few new operators

Like Python, C++ has the compound assignment operators +=, -=, *=, /=, and %=. There’s a few new ones as well:

A full listing of operator precedence can be found here

Coming up next

Textbook Sections 2.4-2.5



Previous: Lecture 00: Intro
Next: Lecture 02: C++ Basics Continued