July 21, 2023

Is C/C++ really a bad decision?

 There are lot of programming languages available. The famous one is Python, but Java, C# and Go are also looking powerful. For writing a software prototype, the Python language is perhaps the ideal choice. Its available in Linux and Windows both and can be used to create all sort of apps and scripts.

The main problem of Python is its performance. Especially for programming games the system is too slow. Even if precompiled third party library are used for example pygame, the framerate in python is too little. Its nearly impossible to write a fast scrolling racing game.

The next better choice over Python is C/C++. C++ is known for its complex syntax. Also the problem with C++ is, that every programmer invents its own programming style. The main advantage of C++ is, that it is much faster and the programmer has more control over the situation. Sure, C++ is harder to learn than Python, but compared to vanilla C and even compared to asembly language, C++ has to be mentioned as a beginner friendly language.

Its beginner friendly because the newbie can create with a low amount of code lines and with the help of existing tutorials a graphical demo like the following one:

// compile with g++ hello.cpp -lsfml-graphics -lsfml-window -lsfml-system
#include <SFML/Graphics.hpp>
#include <iostream>

int main() {
    // init window
    sf::RenderWindow window(sf::VideoMode(640, 480), "Hello world!");
    window.setVerticalSyncEnabled(true);
    window.setFramerateLimit(25);
    sf::CircleShape shape(40);
    shape.setFillColor(sf::Color(0, 0, 250));
    sf::Vector2f position;
    // game loop
    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event))
            if (event.type ==
            sf::Event::Closed)
                window.close();
        window.clear(sf::Color(255, 255, 255));
        window.draw(shape);
        window.display();
        // move
        shape.move(1.f, 0.f);
        position = shape.getPosition(); // = (15, 55)
        std::cout<<"pos "<<position.x<<" "<<position.y<<"\n";
        if (position.x>300) {
          shape.move(-300.f, 30.f);
        }
    }
    return 0;
}


In around 30 lines of code, a ball is shown on the screen which is moving from left to right. The source code compiles into a 24kb large binary file which can be created for Linux, MacOS and Windows. Also the file will need only a little amount of cpu ressources and runs more efficient than the python version.

Sure, the source code looks compared to the python version a bit messy. The programmer has to manual care about many things and it is hard to understand what the code is doing. But for writing a production ready app, C/C++ is the prefered choice. There is no programming language available which can replace this well known and powerful C dialect.

No comments:

Post a Comment