Author: David

A useful function to know- atexit

A useful function to know- atexit

Warning signs
Image by Annalise Batista from Pixabay

This is in C, but applies to C++ as well and is part of stdlib. Perhaps you’ve written a program and when it exits, you want it run some final code. The typical use case for this is releasing resources such as memory allocations and closing files. If you are doing networking then it might also be closing network handles.

Then you need atexit(). You pass in the name of void function. When it finishes, it jumps to that function and runs it. Here’s some code to show it in use.

void ExitFunction(void) {
    printf("Exited");
}    

int atv = atexit(ExitFunction);

As good programming practice, you should check that value to make sure it’s 0. If it isn’t then your exit handler failed to register. I’m not sure what would cause that (overzealous antivirus software?)

You might notice that the ExitFunction has a (void) parameter rather than (). The two are the same but atexit() has been told to expect void parameters and will be disappointed should you fail to comply. Not disappointed enough to give you an error but you will incur a warning and you know how I hate to see those.

The reason why I hate warnings is that not all warnings are equal. This one is trivial and could be ignored, but others aren’t and really need dealing with. So I go for zero tolerance to warnings. Some compilers like gcc have a setting to tell the compiler to treat all warnings as errors.

C is top programming language in Tiobe?

C is top programming language in Tiobe?

Technology
Image by ar130405 from Pixabay

The Tiobe index is a popular and much quoted and updated monthly list of programming languages sorted by popularity. And in May 2020, it lists C as the top language.

Now call me cynical; I do like C (kind of obvious- duh!) but I do have my misgivings about this index. For one, other programming language popularity measures usually disagree with it but are more consistent. Here are some. Most other articles seem to quote from these particularly the StackOverflow developer survey.

RedMonk – C is ninth.

Reddit’s programming language sub-reddits. C is ninth on here.

PyPl – how often language tutorials are searched on Google.  C does not appear at all!

StackOverflow developer survey 2019. C is eleventh in their listed technologies.

Github Octoverse. You have to scroll down to Top languages. C is ninth.

Codingame 2020 Survey. You have to scroll down. C is 6th in most loved and most known (5th in most dreaded!)

Now each of these measures different things so they are never going to be that consistent but coming ninth in three different surveys is pretty telling, with one eleventh and one sixth.  So when you see things like Tiobe, please take this with a pinch of salt.

More on generating random numbers

More on generating random numbers

Two dice
Image by Clker-Free-Vector-Images from Pixabay

The very first program I wrote in any programming language was sometime in October 1976. It was in BASIC and it had this line or something very similar. Even then I was into random numbers. I know, uppercase!

LET DIEROLL = RANDOM(6)+1

I’ve been writing small utility that I’ll publish in a few days. It’s 100% in C and I decided instead of using srand(time(null)) for generating random numbers, I’d use something with a bit more oomph. That something is a library called sodium. Using it for just generating random numbers is a bit overkill. But it has the benefit that the random numbers are good enough random to be used in cryptographic code. Not all random number generators are good enough. This one is.

And it’s easy enough and adds just one dll, or you can compile it statically. I’ll do that once I figure it exactly which Visual Studio settings to change.

It takes just one include –

#include <sodium.h>

Then one call to initialise it.

 int i = sodium_init();
 if (i<0 ) {
   error("Unable to initialise sodium library. Error = ",inttoa(i) );
 }

After that you can call one of several functions. Here’s an example from my code. It fills a 64 byte key with the numbers 0-63 but shuffled like cards.


    typedef char key[64];
    key _key;
    uint32_t ival;
    int i,index1,index2;
    for (i = 0; i < 63; i++) {
        _key[i] = i;
    }
    for (i = 0; i < 1000; i++) {
        do {
            index1 = randombytes_uniform(64);
            index2 = randombytes_uniform(64);
        } while (index1 == index2);
        ival = _key[index2]; // swap two indices
        _key[index2] = _key[index1];
        _key[index1] = ival;
    }

The do loop (how often do you actually see those used in code!) generates two indexes in the range 0-63, making sure that they are not the same. It then swaps the two values at those indexes, and does this 1,000 times. It’s very similar to card deck shuffling code.

Do you know how long it would take you to work through all the combinations of 64 numbers this way? IF you could do a million a second, it would take you 1.27×1083 seconds or 4.02×1075 years! Or to make it more meaningful it’s this large! 4.02,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000. That’s approaching (but still far far off) the time for the heat death of the universe which is estimated at 10100!

The Joys of C++

The Joys of C++

Maze
Image by Arek Socha from Pixabay

My progress on the C++ asteroids game took a little detour down a one way street. The problem I hit was until then I thought I was being clever by passing in a reference to another class in the constructor. That worked fine until I started implementing array classes.

The issue I got was using my constructor meant that the default constructor was deleted. This happens in any class where you add your own constructor as all the special functions are deleted. You then have to add your own Move or Copy assignments if you are doing things that invoke them. Like iterating through an array (or vector in my case). Although I use Bullet and Asteroid classes, I manage  collections of them through an Asteroids and a Bullets class.

Plus I’d decided that vector class wasn’t perhaps the best class to use. This thing runs at 60 fps, so adding and deleting elements from a vector seems a bit wasteful. Instead by using a std::array, and constructing all elements in it when the managing class is instantiated, all I have to do is scan for the first element with an active flag set false. (all are set false when constructed), set a few fields for velocity and position and there it is on screen.

Is this premature optimisation? I don’t think so. One of the things that programmers are told NOT to do!

So I have cleaned up my constructors now. They are parameterless and no special functions are deleted. It’s this kind of stuff that can do your head in and one of the reasons why I think C++ is considered a harder language to master.  I’m certainly a long long way from that.

The maze? Just a metaphor for C++ programming!

Want to learn C by doing projects?

Want to learn C by doing projects?

chess
Image by FelixMittermeier from Pixabay

This site on Github has lots of interesting projects that will help you improve your C programming ability.

Whether it’s  a chess engine, a sudoku solver, space invaders clone,  tic-tac-toe (noughts and crosses for us Brits!), Othello, program a text adventure plus a lot of non games stuff as well.

I’ve added this to the C code Links page.

 

Or do you fancy learning how to write your own virtual Machine in C? Authors Justin Meiners and Ryan Pendleton have crafted a 14 part tutorial that will teach you how to write a VM that can run assembly language programs.

 

A small C++ Tip. Return values from Constructors

A small C++ Tip. Return values from Constructors

C++ LogoYou can’t return anything from a constructor.  One way is to use exceptions but those can bring their own issues. Google’s C++ guidelines actually stipulate no exceptions and I’ve heard it from others as well that they prefer not to use them. Some people avoid it by having a mostly empty constructor and then an init() method to do the real initialisation and return a success/fail state.

But there is a simple trick that you can use, just return the state as a reference. Here’s an example. If you want to return more values, use a struct.

#include <iostream>
using namespace std;

class Simple {
public:

    Simple(bool& failure) {
        failure = true;
    }

    ~Simple() {
    }
};

int main() {

    bool fail_flag = false;
    Simple f(fail_flag);
    if (fail_flag)
        cout << "failed " << endl;
    else
        cout << "Success" << endl;
}
C++ enum class vs enum

C++ enum class vs enum

C++ LogoI’d read about enum class in C++. It’s a slight strengthening of the compiler checking compared to plain old enums.  Why you may wonder? Well,

  • Conventional enums can implicitly convert to int, causing errors when someone does not want an enumeration to act as an integer.
  • Conventional enums export their enumerators to the surrounding scope, causing name space pollution.
  • The underlying type of an enum cannot be specified, causing confusion, compatibility problems, and makes forward declaration impossible.

Additionally you can declare the underlying storage type, which lets the compiler catch bugs where a value is too large for the storage. Here’s a made up example to show this:


enum class byteThings : unsigned char {
Thing1 = 0x01,
Thing2 = 0x02,
Thing3 = 0x04,
BigThing = 0x120  // Compiler will complain!
}

The downside is that to get the int value, you now need to do a static cast but it does make your code safer.

byteThings b = Thing2; 
int i= static_cast(thing); // 2

 

C++ Asteroids is progressing

C++ Asteroids is progressing

C++ AsteroidsThis is a screenshot of it as it stands and yes those asteroids are moving! It looks identical to the C version; the only difference is the code, not the appearance.

What makes it interesting is the structure. The Player and Asteroids classes both inherit from a Common base class that has all the position and move data.

It took a bit of time to get the overall architecture right. There’s a Game class which manages everything; the Player, Asteroid and Lib classes.  But Asteroids and Player classes also use the Lib class so  it took a bit of faffing around to make them all play happily together.

This is the biggest difference between C++ and C; the classes and how they all fit together. My biggest source of frustration has been arm wrestling with the C++ compiler; it sometimes seems as if never get easier! Sometimes a wrongly placed semicolon can generate hundreds of compile errors…

It took half a day to get it right and bullets should fit in much easier. Mind you I’ve had to incorporate two static variables in the Common class. One is a copy of the SDL renderer; this is needed to draw things on screen. The other is a pointer to the Game class so that I can access the DebugFlag state.  This is used to show debug information but I may be able to move the flag itself into the Common base class and change it through a call on a Player method. So long as it is static then changing it for the Player also changes it for the Asteroids and Bullets.

 

Slight change in direction – more C++ and Pi

Slight change in direction – more C++ and Pi

Raspberry Pi
Image by planet_fox from Pixabay

As I said recently, writing about C and games probably isn’t enough to sustain this site, but if I extend it to include C++ and Raspberry Pi and still maintain the overall direction of writing about game development then that I think will do it.

So I’ve added a new page for C++. I’m currently working on the C++ version of Asteroids and making good progress.

I’m striving to write it in modern C++. To that end, the first entry in the C++ page is a link to a very long document: C++ Core Guidelines written by two luminaries of the C++ world Herb Sutter and Bjarne Stroustrup (creator of C++). You should definitely give it a read.

Interesting fact about the Raspberry PI. Did you know that in March 2020, they sold 640,000! That’s pretty amazing! And while that article says that AAA game playing isn’t something you can do on a Pi, we now know that you can run simple 2D arcade quality games on a Raspberry Pi 4.

Raspberry Pi 4 – Perfect for arcade quality games and development

Raspberry Pi 4 – Perfect for arcade quality games and development

lot s of asteroidsI got my Pi 4 a week ago and have been doing experiments on it with my Asteroids game. If I disable the line of code that kills the player ship in the DestroyObject() function and just add a return after case tPlayer: and uncomment the code that adds Asteroids when you press A then I can have lots of asteroids on screen. Also set the MAXASTEROIDS #define to 128.

Then you get the likes of this screenshot which is a 1024 x 768 size window. It’s still running at 40 fps, there are 116 asteroids on screen, around 60-70 explosions and the Pi’s temperature is still a balmy 44.79 C. I’ve never got the Pi’s temperature (and it does have an internal 3.3V fan) to rise above 51 C.

But what’s also impressive is that with Visual Studio Code and Clang on the PI, I can compile the whole 2,200 lines of C on the PI in about a second. This makes the Pi very usable for developing games. And I say this as someone who is used to powerful Windows PCs for compiling code.

This is it running in debug mode; that’s all the numbers and wire frame bounding boxes around every moving object.

Further experimenting and removing the limitations (I used a While loop to limit it to 60 fps back before I had enabled the hardware video flyback). With that while removed and the hardware video flyback disabled, I was getting over 100 fps with 100 asteroids on screen at once.  I pushed it up to 6,000 asteroids and the frame rate dropped to 10 fps. Given the amount of stuff that was colliding and blowing up, that’s still very good.