I just learned Python. Should I learn C++ too?
No. 30
OK, so you’ve made some real progress with Python and are wondering if you should learn another language? Like maybe C++?
Well, this depends on how far along you are. Because C++ is very similar and also very different from Python, and the learning curve is steeper than it was for Python, which was designed to be easy to learn. Consider the following:
C++ requires that you surround all blocks of code with braces {like these}.
C++ requires that every statement end with a semicolon. And not only every statement, but every class as well.
C++ input and output to the terminal is pretty baroque compared to Python’s.
C++ is a strongly typed language: you must declare the type of every variable you use.
Python is an interpreted language, while C++ is a compiled language. This means every time you need to test a program revision, you have to go through a compilation step before you can see if it runs. Python converts the code to byte codes that run pretty much right away.
So, let’s consider a simple program to add two numbers together. In Python that is just a few lines of code:
val1 = float(input("Enter first number: "))
val2 = float(input("Enter second number: "))
sum = val1 + val2;
print('Their sum is: ', sum)
In Python, your program begins execution at the first line that is not part of a function or class. But in C++, execution begins in the main() function. And don’t forget those braces and semicolons!
#include <iostream>
#include <string>
using namespace std;
// Simple program to add two numbers
int main() {
string ans1, ans2;
// get the first number
cout << "Enter first number: ";
cin >> ans1;
float val1 = stof(ans1);
// get the second number
cout << "Enter second number: ";
cin >> ans2;
float val2 = stof(ans2);
// add them and print out the result
cout << "The sum is " << val1 + val2 << endl;
return 0;
}
In the above C++ program, we send a string to the output stream, using the cout function, which prints the string on the console screen. Then, we read the keyboard entry using the cin function, which reads from the console input stream, or keyboard. The result is that we get an input string consisting of the number we typed in. Note that you have to declare the type of each variable before or when you use it. In the above example, we highlighted those type declarations.
Now, to convert that to a float, we can’t just cast it as we do in Python, but instead have to call the stof function (string to float) to return the floating point number we wanted. We do that again for the second number, and then we can add the two converted numbers in val1 and val2, and print them out, again using the cout function.
A function!
Now the discerning reader may notice that the 3 lines needed to get the first number and get the second number are pretty much the same. So, we could put that input code into a function that we call twice. That function is:
//function to read in a number and convert to float.
float getnum(string message) {
cout << message;
string ans;
cin >> ans;
float val1 = stof(ans);
return val1;
This reduces our main program to just:
int main() {
// get the first number
float val1 = getnum( "Enter first number: ");
// get the second number
float val2 = getnum( "Enter second number: ");
// add them and print out the result
cout << "The sum is " << val1 + val2 << endl;
}
Now, this may at first be reassuring, and it should be. But there is a huge amount to C++, much of it rather oblique to the philosophy of Python. For example, you can still use the Visual Studio community edition that you may have been using for Python and write good C++ code pretty easily. Or, if you used PyCharm, that company, JetBrains, makes CLion, a familiar feeling IDE for writing C++ or C code. However, it costs about $89 for the first year and a bit less in following years.
We tried both, and while both are very good, we found that CLion had more help for correcting errors. In many cases, it could fix the code for you. Visual Studio is not quite that helpful, although it flags the errors. Eclipse provides an excellent IDE as well. Here is a list of other C++ development systems.
Performance
So why might you want to write some of your code in C++? Mainly for performance. Python is an interpreted language, as we noted, but because it is dynamically typed, more computations to deduce the type of a variable must take place while it is running. Further, since Python garbage collects variables and arrays that are no longer used, there is a lock on having multiple threads running on the same data. Anthony Shaw does a good job on explaining all this here.
So, how slow is Python? It depends. Note that very often you will call precompiled libraries like numpy that are already optimized C code. But let’s take a example we wrote earlier to compare the performance of the Python map function to calling the function directly.
This simple program takes an array of 6 numbers, squares each of them and puts it in a new array, in this case, a vector:
for (int i=0; i < 1000000; i++){
int ara[] = {2,3,6,8,5,4};
vector <int> v={0};
for (auto a: ara) {
v.push_back(sq(a));
}
We found that the Python version ran those million repetitions in 1.28 seconds. This C++ version is only slightly faster, at 1.08 seconds. However, if we comment out what appears to be the very slow vector creation and just store the data in an array
for (int i=0; i < 1000000; i++){
int ara[] = {2,3,6,8,5,4};
//vector <int> v={0};
int dest[6];
int k = 0;
for (auto a: ara) {
//v.push_back(sq(a));
dest[k++] = sq(a);
}
}
we find that this version runs in 29 milliseconds, about 500 times faster than the Python version. Changing the Python version to use a pre-allocated array made no difference in the Python timing.
Conclusions
So, C++ is faster, and there are a number of great development systems available. But C++ has a much longer learning curve than Python does. We wrote a book on C++ sometime late in the last millennium, and I must say, C++ has grown and changed so much that we pretty much had to start over. Some of the best features of Python have crept into C++, like the for range iterator and the vector. And C++ version 20 even has something close to f-string formatting, although I haven’t yet found it in any of the IDEs we’ve tried.
But the real advice comes from gymnastics. If you plunge into C++ before you are solidly and confidently writing Python code, you are likely to get “the twisties.” You will be pulled in different directions at every moment because you are still learning two quite different languages. So, yes you should learn C++ eventually, but don’t let it intrude on your becoming proficient in Python!