C++ is a language derived from the C programming language.
C++ has good support for Object-Oriented programming.
C++ has poor support for Higher-Order Functions and zero support for lambda functions.
C++ allows code to manipulate memory (both powerful 💪🏽 and dangerous 🤕).
C++ is fast
Why to care? C++ is used in the next two CS courses:
Unlike Python, which is interpreted, C++ is compiled down to the machine language and the executed directly by your Operating System (OS).
In CS 235, you will learn how to compile C++ programs. For this course, we'll use an online compiler (the compiling and execution process happens on some server out on the web).
There is an online compiler option here: https://www.w3schools.com/cpp/cpp_compiler.asp
Python is dynamically typed (sometimes called untyped, but this term is misleading)
C++ is a statically typed language, which means that all data must have a known type before the program is compiled
In Python statements don't have any special ending.
But in C++ all statements must end with a semicolon ;
In Python scope is determined by indenation.
But in C++ scope is denoted with braces{ }
In Python we can change the type of the value bound to a name.
x = 14 # note there is no type or semicolon
type(x) # <class 'int'>
x = 'hi there'
type(x) # <class 'str'>
The above is not allowed in C++. Once we create a variable of type int
called x
, x
can only be assigned values of type int
.
Note: only values have types in Python, but in C++ both names and values have types
In Python all variables are just a name bound to some value.
x = 14 # note there is no type or semicolon
type(x) # <class 'int'>
In C++ all variables must be given an explicit type before the variable name.
int x = 14; // note the semicolon
Here are the built-in types we've used with Python:
C++ only has 3 of these 6 types built-in:
What?!? 😨
C++ doesn't have built-in strings, lists, or dictionaries?
vector
class this is similar)map
class that is similar)We will see vector
s and map
s in detail later.
The C++ boolean type is bool
and has values true
and false
.
bool repeat = true;
There is no third boolean type in C++ (like None
in Python).
There are two floating-point types in C++: float
and double
.
double
has double the precision (twice the storage size) as float
.
Common practice is to always use double
when on a PC (float
is usually only used on embedded devices with restricted memory).
float grade = 0.85;
double rate = 1.3;
C++ has multiple integer types that can hold numbers of different bit sizes.
C++ has both signed
and unsigned
integer types
signed
types are numbers that can be both positive and negativeunsigned
types are numbers that can only be non-negative, always >= 0C++ integers have sizes that can vary, depending on the processor for which the code is compiled 🤯
Type | Signed/Unsigned | Size in Bits |
---|---|---|
short int |
Signed | at least 16 |
unsigned short int |
Unsigned | at least 16 |
int |
Signed | at least 16 (often 32) |
unsigned int |
Unsigned | at least 16 (often 32) |
long int |
Signed | at least 32 |
unsigned long int |
Unsigned | at least 32 |
long long int |
Signed | at least 64 |
unsigned long long int |
Unsigned | at least 64 |
In practice, usually only int
and unsigned int
are used.
int
is often 32 bits, so it contains the numbers in the following range -2^31 through 2^31-1
or -2,147,483,648–2,147,483,647
unsigned int
has a range from 0 through 2^32-1, or 0–4,294,967,295
The unsigned integer type is used when a variable should only store a non-negative number (like the size of something), but we often just use int
for most numbers.
int year = 2022;
int month = 4;
int day = 1;
C++ has a string type called C-strings which come from the C programming language
"
, i.e. "hi there!"
' '
like in PythonC++ has a string type that is a class called string
that comes from the C++ Standard Library
// variable is type `string` and value is type `C-string`
string name = "Grace Hopper";
Here are some common methods provided by the string
class:
Method | Parameter(s) | Description |
---|---|---|
at | int — index | Accesses the specified character with bounds checking |
front | (none) | Accesses the first character |
back | (none) | Accesses the last character |
c_str | (none) | Returns a immutable C-string version of the string |
empty | (none) | Returns true if string is empty, false otherwise |
size/length | (none) | Returns an unsigned integer type with length of string |
Many, many more. See C++ Reference.
The C++ Standard Library provides the class string
that is similar to Python's str
You must import this class in C++ style (at the top of your file):
#include <string>
Since the string
class is in the Standard Library, you need to use std::
before the name string
.
std::string nasaEmployee = "Katherine Johnson";
printf("The third character in the string is: %c", nasaEmployee.at(2));
C++ arrays are a an ordered group of contiguous memory addresses. The square brackets [ ]
are used to denote arrays.
To define an array type, the type for all elements must also be explicit; the size of the array must also be given.
Here is code to create a variable of type array of integers:
// now the name 'values' is a variable that stores ten integers
int values[10];
To access an element in a C++ array we use the square brackets [ ]
, just like with Python lists
// set the first element in the array to the value 13
// (it must be an integer array or this will not compile)
values[0] = 13;
int first = values[0];
To create a literal, or value, of type integer array we use the braces { }
Here is code to create a variable of type array of integers and initialize it with specified values:
int values[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Note that we don't need to provide the size if we assign the variable to a value of type integer array.
The C-string type is just an array of characters, or char
type.
// note you don't need a size for this array either
char name[] = "Edsger Dijkstra";
Once created, an array's size cannot change. Also, the size of the array is not stored! 😱
int SIZE_OF_VALUES = 10;
int values[SIZE_OF_VALUES];
The above code has a problem if the variable SIZE_OF_VALUES
is ever assigned a new value
C++ has the const
keyword to say that a variable must be constant (i.e., its value is never allowed to change).
Now we have the following code:
const int SIZE_OF_VALUES = 10;
int values[SIZE_OF_VALUES];
Upon creation of a C++ array variable, all the elements contain ⚠️ garbage values ⚠️ unless you assign each individual value or the variable to an array of values.
const int SIZE_OF_VALUES = 10;
int values[SIZE_OF_VALUES];
// we have no idea what values[0] will contain,
// except that it will be an integer
int value = values[0];
There is no special keyword like def
in C++ functions.
Function definitions follow this EBNF pattern:
TYPE identifier "(" [TYPE identifier ["," TYPE identifier]*] ")" "{" statements "}"
For example,
int add(int a, int b) {
return a + b;
}
Note the braces are needed { }
since C++ doesn't care about whitespace — but you should still use good indentation!
C++ originally did not have good support for Higher-order functions and had no lambda functions 😭
Higher-order functions and lambdas were introduced in C++11 (the 2011 version) and have continued to improve in C++14 and more recent versions. They are still more rarely used (many C++ courses don't cover them).
C++ code always starts with a special function called main
, which always returns an int
. Standard practice is to return 0
if the code worked, a negative number on failure.
main
takes arguments from command line so it has parameters int argc, char* args[]
— first parameter is the number of C-strings in the second parameter, which is an array of C-strings, or main
can have no parameters.
int main(int argc, char* args[]) { ... }
int main() { ... }
Convention is to create a main.cpp
file for the main
function:
#include <cstdio> // for 'printf' -- or use #include <iostream>
int main() {
printf("Hello, World!");
return 0;
}
def interest(rate, years):
return 1 + rate * years
print(interest(0.002, 5))
#include <cstdio>
double interest(double rate, int years) {
return 1 + rate * years;
}
int main() {
printf(interest(0.002, 5));
return 0;
}