Programming in C++ the right way

The C++ programming language is the best technique in implementing modern software. It’s a great choice for Linux, Windows and Mac OS X. The main reason, why C++ is superior to Python, golang, Java, and C# is it’s performance. No other language can provide the same speed, and C++ compiler are the most professional available. If a modern software project provides precompiled binaries for all the major operating systems it is the best practice method in deploying software for production environment. That means, the enduser won’t have much trouble in running a .exe file which was created by a C++ compiler on his operating system.

The only problem with C++ is, that most beginners finds it hard to master. The language provides a large amount of features. Let us first describe a situation, which can be handled very well with the C++ programming language. Suppose, the programmer has already a prototype written in the Python language. It’s a simple pong game. The task is now to convert this prototype from Python to C++. That means, to rewrite the sourcecode in C++ and optimize the sourcecode for maximum speed. How hard is this task? Not that great. It’s a C++ only programming task. That means, how the software will looks like is defined in advance, all the classes are known thanks to the Python prototype. And the C++ programmer has only to write the sourcecode itself, which is using the latest C++ features. Then he compiles the project into a binary file and the game will run great.

The amount of needed manpower for such a conversation task is also very low. A single programmer can do so. Even his knowledge about C++ itself is low, he will find in the internet all the ingredients he needs. If he runs into trouble with pointers, he will find the answer too and at the end, the programmer will notice, that pointers are easier than expected and they improve the stability of the code very much.

Most C++ programming projects doesn’t start on top of existing prototypes written in Python and this is the reason, why C++ is sometimes called problematic. If C++ is utilized for creating a prototype, it’s indeed a Honorable language. Because the programmer is not allowed to make single mistake. The syntax must be perfect, and it’s hard to try out new ideas. Using C++ as a prototyping language and communicating the results with other developers is some kind of antipattern. That means, the developer will waste his time with complicated C++ syntax and the project will take months and years without any results. Before somebody can write C++ code, he needs the program first. That means, the class diagram, the documentation, the requirements, the GUI layout, the sprites, the backgrounds, the music and the concept of the game should everything be ready. C++ is only used for creating the final binary. That is a large .exe file / package which will run with maximum speed in a production environment.

The difference between production software and prototyping software is not made clear in the past. The reason was, that most projects in the 1980s were small in size. If the software contains of less than 1000 lines of code, there is need for a dedicated throwaway prototype. Instead, the programmer can write the code from scratch in the C++ language. Such kind of small projects are no longer available. Professional software development requires at least two steps: prototyping design, and programming itself. For that last step, programming itself, C++ is great, because it’s a combination of a compiled language which provides object-orientation. No other language can offer this mixture. Such a combination is important if the project is larger, for example a desktop application, and the binary file should run as fast as possible. Avoiding object-orientation and fallback to plain C isn’t an option, especially not for GUI development. And not using a compiled language and creating a production ready software with Python is also an antipattern, because the Python VM is slow, doesn’t supports pointers and the threading isn’t stable.

What is important to know, that C++ should only be used in the programming step and not for the whole software engineering workflow. Everything which is done before the programming itself, can be created with other tools, which are better suited than C++. For example with graphical UML design tools and with interpreted toy-languages like Python, Matlab and PHP.

Example As a practical example, let us take a look at a Python prototype on Rosettacode. The problem of finding prime numbers can be solved with the Eratosthenes. The Sourcecode for the algorithm is given here https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Python The code has one advantage and one disadvantage. The pro is, that the code is easy to read, the con is, that the Python code will run very slow and can’t be made faster. We are taking this Python prototype and write the same algorithm again in C++. This task is surprisingly easy. We can use the full power of a compiled object-oriented language and the code will run at least 10x faster than the Python original.

Such kind of conversation step is recommended for all projects. At first, some kind of pre-step is needed, which is often equal to a Python program which runs reasonable well but lacks in terms of professionalism. Then this sourcecode is converted into the C++ syntax and will result into maximum performance on any computer architecture.

This strategy provides the following advantages: it reduces the invested manyears, it provides the maximum speed of C++, it is beginner friendly.

Advertisements

Examples for well written software

Which programming language is the best? The answer is not that hard, it’s C++. But C++ alone doesn’t make a well project. On github, many C++ projects are available which don’t compile very well which have major bugs and the software itself is boring. Only if C++ is combined with a good documentation and precompiled binaries for all operating systems, the software will become great. A good example is given by https://primesieve.org/

It’s not a large scale project, but an amateur prime number generator. The algorithm is an improved sieve version which computes very well the prime numbers. But I’m not citing the project, because the task itself is amazing, but because everything around the project is well. That means, there is documentation including a screenshot, there are precompiled binaries, the sourcecode is available and it was written in C++ and Qt. What the enduser can do is to download the 4 mb file. He has to select if he prefers the Windows, MacOS or Linux version. He can test the program on his own machine and if he thinks it sounds good, he can take a look into the sourcecode which is well documented.

I would call the program a production ready software. It is not trying to invent the wheel twice, but is using the normal C++ infrastructure for providing middle class software. What would happen, if the project would switch the programming language? A switch to Python would reduce the processing speed. The prime number generator needs a fast executable file and only C++ can provide this performance. A switch to C# and Java is possible in theory. The overall speed would remain the same. On the other hand there would be no advantage. That means, Java and C# are not better than C++.

Writing C++ gui apps made easy

C++ is known as a powerful but complicated language. Compared to Python, C++ is indeed harder to learn. Writing a simple GUI app with Python is not a big deal. Thanks to tkinter and the well documentation in the internet, even beginners can create their first GUI app on day 1. If the aim is to test out only a prototype but not deploy the software in a production environment, Python is here to stay. But sometimes, the user needs software written in C++ because of performance reasons or because he want’s to use the software in reality. Then he needs to rewrite the code in C++.

The good news is, that from the programming side, C++ is easier than expected. A simple GUI application can be realized with the following sourcecode:

// library install: dnf install gtk3 gtk3-devel gtkmm30 gtkmm30-devel
// g++ `pkg-config --cflags --libs gtkmm-3.0` file.cpp
#include <gtkmm.h>
#include <iostream>

class GUI : public Gtk::Window {
public:
  Gtk::Button button1;
  Gtk::Button button2;
  Gtk::Label label1;
  Gtk::Entry text1;
  Gtk::Fixed fixed;
  void on_button_clicked() {
    int result=std::stoi(text1.get_text())+10;
    std::cout << "The Button was clicked."<<result<<"\n";
    label1.set_label(std::to_string(result));
  }
  GUI() {
    set_title("Frame Example");
    set_size_request(500, 300);
    label1.set_label("Hallo");
    button1.add_label("button 1");
    button2.add_label("button 2");
    button1.signal_clicked().connect( sigc::mem_fun(*this, &GUI::on_button_clicked) );

    add(fixed);
    fixed.put(label1,0,0);
    fixed.put(button1,10,150);
    fixed.put(button2,120,150);
    fixed.put(text1,10,50);
    show_all_children();
  }
};

int main(int argc, char *argv[])
{
  auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");
  GUI mygui;
  return app->run(mygui);
}

It was used the fixed frame layout, which means, that the widgets have absolute positions on the screen. It the button should be somewhere else, only the coordinates have to change. The compilation of the software is done in the operating system environment and the result is a 80 kb executable file which runs smoothly.

in contrast to a Python GUI, the amount of code lines is longer. Also pointers are used. That means, it takes longer to create a gui app in C++ than in Python. But if the aim is to create an executable file the additional effort make sense. It is possible to create large professional GUI apps with C++. In reality it’s mostly a copy & paste technique. That means, if somebody has tested out that his first hello world program rurns, he can take the code and create program 2, 3 and so on. That means, all the GUI apps containing of buttons, textentry fields and tables and the principle in updating the content is equal.

What i want to explain is, that a combination of Python and C++ works great for 99% of the use cases. Python is the best language for quick prototyping. It allows to create throw away sourcecode for testing out new ideas. If the prototype is working great, the software can be reprogrammed in C++ which provides the maximum speed can be compiled for major operating systems like Android, Windows and Linux.

Python vs. C++

The difference between a Python program and the C++ counterpart can be measured in the task manager. Python programs have the property to occupy lots of ressources. A typical pygame instance which displays a game with 40 fps will produce a system load of 30%. On older computers even more. In C++ everything is more efficient. The same game will need less than 3% and the memory consumption is smaller. The reason is, compiled sourcecode is using the ressources more efficient. A general hint is, that compiled code is around 10x faster. Another advantage is, that C++ code can be fixed while Python is always a bottleneck. If a python game doesn’t run smoothly the programmer can’t improve the situation. That means, Python is slow and nobody will change it. In case of C++ there are many way to tune the software. A second advantage is, that most C++ libraries are fast as default.

I wouldn’t recommend C++ against Python. Both programming languages have their niche. Python is great for fast prototyping. No other language is more beginner friendly, and allows to test out an idea. Python is some kind of modelling clay. In contrast, C++ is a professional language. It is used for creating runnable code in real projects. No other language than C++ is faster or has more features.

How to speed up C++

The C++ language has some features, which makes it a great tool for implementing algorithms in software. They are: support for object-oriented programming, a fast compiler, support on all operating systems and working together with existing c libraries. To get familiar with the C++ language an example is helpful which is finding prime numbers. The first version of the program contains of a subfunction which determines for a number if it’s prime or not.

// max=200000, time=66 seconds

#include <iostream>
#include <math.h>

int prime(int number) {
  int result=1; // number is prime
  for (int i=2;i<number;i++) {
    if (number%i==0) {
      result=0;
    }
  }
  return result;
}

int main() 
{
  for (int number=2;number<200000;number++) {
    if (prime(number)==1)
      std::cout<<number<<" ";    
  }
  return 0;
}

After executing the code it takes 66 seconds until all prime numbers from 0 to 200000 are determined. The program works correct, but it’s not very fast. Let us try to increase the speed. The following sourcecode contains of two major modifications, first it will stop the for loop after a prime number was found, and secondly it searches only for number until a threshold which is max/2. This reduces the needed execution time.

// max=200000, time=3 seconds

#include <iostream>
#include <math.h>

int prime(int number) {
  int result=1; // number is prime
  for (int i=2;i<number/2;i++) {
    if (number%i==0) {
      result=0;
      break;
    }
  }
  return result;
}


int main() 
{
  for (int number=2;number<200000;number++) {
    if (prime(number)==1)
      std::cout<<number<<" ";    
  }
  return 0;
}
your code here

Why the world is loving C++

Sometimes, C++ is called an ugly programming language, similar to a dinosaur which doesn’t fit into modern times. This critical point of view is often explained with certain elements of the language, for example with the complicated templates, the pointers or the fullblown compiler which is needed as a backend. To analyze a programming language on an objective basis, not the syntax or the C++ standard is important but the community around a language. This can be identified by searching for C++ books. The amount of published books is very huge, they are created for all worldwide languages like French, german and English and every month new books with the title C++ for beginners are introduced at the bookstore. Buying them all is not possible, and most books are repeating the same knowledge. But it seems, that many people have the desire to write about C++ and other have a demand for reading such books. And that is a sign, that C++ is well alive. It is the most used programming langauge in the world.

Let us take a look into one of these books. They are usually large. 800 pages is the minimum, some books have over 1200 pages. It is divided into chapters like functions, object-oriented programming, usage of libraries, string handling and so on. The main reason, why C++ is so successful has to do, that any problem can be solved with the language, and the exact way in doing so is given in the book. No matter if somebody want’s to access a database, needs a gui for an application or trying to search for a string in a HTML website, he can do so with C++. It is all included in the standard and all is documented very well. From a certain point of view, C++ is an easy to learn beginner language, because the newbie has only to read the information already there and is not forced to invent anything twice.

On the first look, C++ looks very complicated, but programing in C++ is an easy thing. It’s simply not possible that somebody will recognize a problem which can’t be solved with C++. It is all given in the book or otherwise the information can be found at Stackoverflow. C++ itself is not very elegant. Compared to the Forth language, C++ is bloatware, but the amount of information about C++ is much higher. This makes it easier for the newbie to get familiar with the language.

Sometimes, C++ is compared with Python. And indeed, Python is also an interesting language which has a more cleaner syntax. The disadvantage is, that Python can’t be used for writing productive code. A game realized with pygame will become very slow and an database written in Python is not very efficient programmed. Python is a good prototyping language, but C++ is the queen in programming if production ready software is needed.

Is C++ easy or hard to learn? C++ can be called an easy to learn language. It is harder to learn than Python, but all the features are written in the C++ tutorials, that means if somebody is not familiar with C++ he can read the book and then he can write any kind of application. This makes C++ to a universal language. If somebody is interested in writing software he should learn C++, and he will become a quite good programmer.

The only disadvantage of C++ is, that it is attractive for the mainstream. That means, if somebody stays within the C++ universe he will do the same what everybody else is doing. C++ is not an elite language spoken by a handful of experts, but it is some kind of cheap universal programming language which is used by millions of programmers worldwide. No matter if they are creating code for Linux, MacOS or Windows, they are all using C++. That’s the reason, why C++ is called a conservative language. It is used in existing hardware/software environments. That means, a standard CPU and a standard operating system is optimized for C++. If somebody is interested in programming code for the x86 architecture and especially for Microsoft Windows, C++ is some kind standard. That means, it is the main road in the town, which is working great. Finding some issues in C++ is not possible. The only reason why somebody doesn’t like C++ is if he is interested in testing out some non-conventional stuff. For example, if somebody is trying to build new operating systems, new programming languages and new CPU design, than C++ is not the best idea.

Benchmarking Forth vs. C++

In mainstream programming, the C++ language is some kind of quasi standard. It is used for library programming because C++ is the fastest language available. A C++ compiled program will run faster than a Python program which implements the same algorithm. From a C++ perspective, all other languages like Java, C#, PHP or Lua are obsolete, any problem can be solved with C++ only.

What happens if we compare C++ with Forth? The first comparison is done on the same machine which is a standard x86 Intel CPU. The result is, that a modern Forth compiler like swiftForth will execute the algorithm in the same speed like a C++ compiler would do. That means, a prime number algorithm which takes in C++ 10 seconds, will need with SwiftForth the same 10 seconds. The reason is, that SwiftForth is an optimizing compiler. It is able to generate fast assembly code from the Forth sourcecode. But what will happen if we are change the underlying hardware? That means, we are comparing a C++ compiler on a x86 machine, with a dedicated Forth CPU for example the ep32 softcore. The result is, that Forth will be faster. Or to be more explicit, a single operating in Forth needs less Joule than a single operation in C++. The reason is, that Forth eliminates overhead which is inside C++ compilation and x86 assembly execution.

How much is the difference? It is huge. Forth advocates argue, that Forth is 10x more efficient, other say that Forth is 100x time efficient than C++. But if Forth is so great, why is C++ widespread used? The bottleneck of Forth is, that a stackmachine isn’t able to parse a classical language. Register machines are widespread used, because with the help of compilers it is possible to program them in any language. For example in C++, C, Fortran or Pascal. That means, the language engineer thinks about a new language he wants to use, the compiler writer builds the compiler/interpreter for that language and the registermachine executes the assembly statements.

Forth works the other way around. On a Forth CPU the only allowed programming language is Forth. In theory, it’s possible to build a C to Forth converter and it was done so in the beginning of Forth, but this programming style isn’t recommended. It will reduce the efficiency. Only software written in Forth will run great on a Forth machine.

Forth is a wonderful software / hardware but the programmer has to learn Forth first to use it’s power. And this is the real bottleneck. How many developers are able to program in Forth? Not so much. And because Forth is a bit complicated to learn, it was ignored over decades. The bottleneck of Forth isn’t the technology. Forth related hardware and software is the fastest one ever invented. The bottleneck is to explain to mainstream developers what r>, swap and negate means.

Rewriting an application in C++

The debate around which programming language is the best works with a certain assumption in mind. In most cases, the idea is to write software in a programming language and doesn’t change this language. But this is not the reality. A software project contains of at least two separate steps: prototyping and programming. Prototyping is everything which is needed for the code can be written for example to design the gui to the invent an algorithm. The advantage of dividing a project into two parts is, that it can answer much easily what the best programming language is. Or to be more specific, what the best language is to rewrite sourcecode.

Suppose, we have a prototype written in Python and want to reprogram this prototype. The reason why is simple: because Python is slow, doesn’t run on Smartphones and is not standardized. That means, Python code which runs a week ago stable will make problems in the next week only because the new python3 interpreter provides new feature. How can we rewrite the code? The first question is to identify the target language, this can be C++, Java, Forth or plain C. All of these languages has weakness and strengths. But the most important fact is, that rewriting code which is already there is a different kind of task then to program software from scratch.

Suppose we want to create an application from scratch. Then we have to answer if it’s a game, a database application or a command line tool. If we only want to rewrite an app we didn’t have to figure out how the apps works internally. Because the sourcecode, the algorithm and the gui is already there and the question is only how to code the software again in C++. Rewriting given a code again is much easier. It can be done in a smaller amount of time.

Today’s best language for rewriting an application is C++. The reason is, that C++ is very fast, executes on all important platforms and many developers are able to understand the syntax. In contrast, C++ is a bad choice as a prototyping language. Because the code must be compiled first, writing a GUI in C++ is complicated and many standard situations are not supported by libraries. Let us define some kind of antipattern for software engineering. A waste of time is to create the prototype in C++ and then rewrite the application in Python to run it on mission critical systems. The problem with Python as a target language is, that it’s performance is weak. Python is an education language but not the right choice for mission critical systems. Especially not, if performance counts.

But why is the concept of rewriting an application is not more often discussed? Perhaps the assumption is, that it takes to much time to write a software twice. And at the end, two versions are available one in Python and the second in C++ which has to be updated separately. What most programmers are doing is to avoid such confusion and they are searching for the ultimate programming language which is good for prototyping and programming itself. That is the reason why so much language1 vs language2 comparisons are available because the goal is to take a choice. But there is no need for defining a language, it depends in which phase the project is. And rewriting code again doesn’t take too much time. Instead, it will save a lot of it.

The important question here is how long does it take to rewrite an existing Python application in C++. The answer is, that it is surprisingly easy. The reason is, that C++ is a great language for writing large scale apps, it is possible to create modules, classes and control everything with the git version control system. If a prototype is available and the developer can take this for creating the C++ code they will succeed in 100% of the cases. That means, pure rewriting projects will never fail. The real bottleneck in software development is not the rewriting task but the prototyping of a new application. That means to identify new algorithm, to play with the GUI interface and write the documentation. This task eats much time and this kind of subproject has the tendency to fail. The reason is, that nobody knows how to write a prototype. Because the users doesn’t know what they want, the experts are unsure about the best algorithm and the requirements are high.

Software projects can be divided into two subgroups. The prototyping task will fail always, takes a lot of energy and needs many iterations. On the other hand, the rewriting task is always successful, can be done in a short amount of time and the product will perform very well. Because the characteristics are so different, it make sense to separate between them.