Comparing python and C++#
Python and C++ have a number of similarities but also important differences that we will encounter when we apply our C++ knowledge to writing python programs.
Similarities#
Both are object-oriented languages, and use the
.operator as the member-access operator. We will write classes and work with objects in the same way.Both have a robust standard library that provides many of the same features. For example. the python equivalent of
std::vectoris a list.The C++
std::formatlibrary was inspired by python, and the same formatting syntax works.Floating point math works the same way—both languages follow the same IEEE standard and have single- and double-precision math.
Differences#
python is an interpreted language
We run a python program by doing
python program.pyC++ requires using the compiler (e.g.
g++) to translate the source into machine-specific instructions
python is dynamically typed—we don’t need to specify ahead of time what type of data a variable/object refers to, while all objects in C++ must have their datatypes specified ahead of time
python# a floating point number x = 2.5 # an integer a = 1
C++double x{2.5}; int a{1};
python statements typically end at the newline.
C++ uses a semicolon,
;, to terminate a statementpython uses whitespace to denote code blocks for
if,for, functions, etc.pythonif x > 0: print("x is positive")
C++if (x > 0) { std::cout << x << std::endl; }
integers behave differently in python, in 2 important ways
integer division results in a float, i.e.
1 / 2is0.5in pythonThe size of an int (in bytes) expands as needed, so there is no overflow, i.e., we can store
a = 123456789012345678901234567890
python can be slow. Scientific libraries (like NumPy) and avoiding loops can help.
C++ is generally fast if you use modern language features and compiler optimization.
python scope works differently than C++.
pythonx = 10 if x > 0: y = x + 1 # we can access y here
C++int x{10}; if (x > 0) { int y = x + 1; } // we cannot access y here
python doesn’t have references and pointers. However, the standard python interpreter is written in C, so those concepts still exist behind the scenes.
An important way this comes up is in passing objects to functions.
In python, we can think of objects as passed by reference, not value (see python data structures).
In C++, when we pass objects to a function, they are passed by value, unless we make the function argument a reference (add the
&).