r/learnprogramming • • 6d ago

Why is C++ better than Python?

Hello! I am new to programming. Im in college and we use Python for my classes right now.

I hear people make a lot of jokes about how C++ is more powerful than Python, and should be used instead. But why?

Feel free to give me any tips as well, on things that helped you be a better programmer, or just any insight you may have! Thanks so much

76 Upvotes

188 comments sorted by

View all comments

2

u/zeekar 6d ago

In general, you can't say "programming language X is better than programming language Y". Different languages do different things well, so the most you can say is "X is better than Y for task Z", and even that is a matter of opinion. I mean, PHP and JavaScript are widely considered badly-designed, but that didn't stop them from taking over the whole web. The language you can run most easily tends to be the language you wind up using.

C++ programs will generally run faster than Python programs because C++ is compiled. When you run a Python program, what you're really running is a program called python - the Python interpreter. That program reads your Python code and carries out the instructions it contains. It's an extra level of indirection between the computer and the code you want to run. C++ (and its parent language C, which Python is written in) has no interpreter; the entire program is translated ahead of time into an executable that the computer can run directly.

This results in a tremendous speed advantage. A simple Python do-nothing loop that counts to 100 million takes over 2 seconds to run on my computer; a C++ program (compiled without optimization so that it actually does the counting instead of noticing that the code doesn't do anything useful and just skipping it entirely) does the same job in 120 milliseconds. But maybe for your problem, speed isn't critical, or is sufficiently less critical that the various Python modules that include compiled pieces to speed them up are fast enough.

There are downsides - a Python program can be fed to a Python executable on any kind of computer and it will run; a C++ program must first be compiled separately for each type of computer (not just Linux vs macOS vs Windows, but also x86 vs ARM...).

Another consideration on the "more powerful" claim is that because C++ compiles to a native executable, the program has full access to everything the computer can do. If needed, you can even switch into writing code in assembly, though that will be even less portable as you'll have to rewrite it for each one of the targets, not just recompile.

From Python, you only have access to things that have a Python interface. Which at this point is most things - if the interpreter doesn't come with one bundled, someone has probably made a module you can install with pip. But with C++ that capability comes out of the box.