Author: David

Updated, how I track designs

Updated, how I track designs

Dendron logoBack in August I mentioned WikidPad which I had been using for ideas, design notes etc.

Recently though while waiting to get my Windows PC sorted, I’ve been doing nearly everything on an old laptop that I’ve repurposed by installing Ubuntu. All blogs since March 6th have been done on this laptop.

Today I came across Dendron which is a markdown editor (on steroids!) that runs in VS Code. Anyone who reads this blog knows that I’m a big fan of VS Code so it’s a no-brainer to combine the two.

Markdown is a way of annotating text for example *this phrase* will appear in italics. Dendron lets your have a split view so you type in the markdown text on the left and the page appears on the right.

The idea is that you create your document out of lots of pages, that are hyper linked. Dendron makes it easy to create pages and link them. Markdown is used to add formatting. WikidPad used a similar scheme but it was a Windows application holding pages in a SQLite database not an extension to VS Code as Dendron is that holds pages as individual text files.

Dendron appears a lot more powerful so I will be getting to grips with it. It’s a handy way of designing and documenting a design.

 

 

Is variable++ faster than ++variable?

Is variable++ faster than ++variable?

TimingsOne of the things I as told when I learnt C++ and then later C was that a post-inc (i.e. variable++) was faster than a pre-inc i.e. ++variable. Frankly I’m not sure if it is really true but its not a difficult thing to test.

Here’s a short program

#include <stdio.h>
#include "hr_time.h"

#define NUMLOOPS 100000000

int main() {
  stopWatch s;
  startTimer(&s);
  int j=0;
  for (int i=0;i<NUMLOOPS;i++){
    ++j;
  }
  stopTimer(&s);
  printf("PreInc = %10.5f\n",diff(&s));

  startTimer(&s);   
  j=0;
  for (int i=0;i<NUMLOOPS;i++){
    j--;
  }
  stopTimer(&s);
  printf("PostInc = %10.5f\n",diff(&s));  
}

You can get the siurce code including hr_time.h and .c from the timings.zip file on GitHub. I used VS Code with clang to build this on Ubuntu. Here is the tasks.json file to build it. It assumes that the file is in your workspace folder and creates a file called ex1. The timings.zip file contains the json files as well.

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "clang build active file",
            "command": "/usr/bin/clang",
            "args": [
                "-g",
                "${file}","${workspaceFolder}/hr_time.c",              
                "-o",
                "${fileDirname}/ex1",                
                "-lm"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Ignore the first three runs which were for 10 million not 100 million. All do indeed show that post-inc is indeed faster. Not by a great margin but each of the last 100 million loops takes between 94% and 96% of the preinc time.

Interesting gcc/clang extensions to C

Interesting gcc/clang extensions to C

C ExampleBoth gcc and clang support extensions to C and while i normally try and make things I write about work on Windows (i.e. Visual Studio), these are useful enough that I thought they deserve a mention. Yes I know you can run gcc/clang on Windows using Cygwin or MinGW, but for various reasons I prefer Visual Studio.

You can add a constructor and destructor functions to a C program; the constructor function runs before main() and the destructor after main().

The syntax is not exactly clean or obvious (those are double underscores before and after the word attribute like Python dunders!) but I got this program to compile/run with clang 10 on Ubuntu as the screenshot shows.  Here’s a listing. I called the two functions ctor and dtor but you can use anything.

#include <stdio.h>

__attribute__((constructor)) void ctor(void)
{
  printf("Constructor runs first\n");
}

__attribute__((destructor)) void dtor(void)
{
  printf("Destructor runs last\n");
}

int main() {
    printf("Main\n");
}

The output  is:

david@DavidPC:~/Projects/Examples$ ./ex1
Constructor runs first
Main
Destructor runs last
Cling – an interactive C++ interpreter

Cling – an interactive C++ interpreter

Computer screen
Image by Markus Spiske from Pixabay

When I first learned to program back in 1976, I had a teletype and a BASIC interpreter. Apart from a couple of years writing BASIC programs in my first job, all my work after that was with compilers.

So I’m a bit rusty with interpreters. The idea is that the interpreter reads a line of code and then executes it; parsing it and calling various routines to execute statements and parse then evaluate expressions. It’s kind if unusual to do this with C++. Cling is built on the top of LLVM and Clang libraries.

This is different to sites like repl.it, codepad.org or ideone.com; they compile the whole program and run it. With an interpreter, it runs line by line and you can print out variables at any time.  Interpreters are probably more like debuggers.

As well as C++, cling can execute C, Objective-C and that even less used language Objective-C++.  Developed at Cern it has a very extensive set of tutorials.

Warzone-2100 C++ cross platform open source

Warzone-2100 C++ cross platform open source

Warzone 2100
Image from Wikimedia

There are some amazing open source games available and Warzone 2100 is definitely one of them. It was originally developed by Pumpkin Studios and published by Eidos Interactive. It was originally released in 1999 on PC and PlayStation.

In late 2004 the source code and most of the data was released and a few years later the rest of it. It is now also available for Windows 7-10, macOS, FreeBSD, AmigaOS, AROS, MorphOS, Linux, NetBSD and OpenBSD. Since then the Warzone 2100 Project has been worked on.

According to the GitHub page “Command the forces of The Project in a battle to rebuild the world after mankind has been nearly destroyed by nuclear missiles. “. You can play it in single-player mode or against other players on a LAN or on the internet.

To get a feel for the game you can view the online guide.

Once you’ve played it, you could consider contributing to the project. It’s an open project and the issue tracker currently shows 213 open issues.

 

 

 

Nearly finished translating asteroids to C++

Nearly finished translating asteroids to C++

Asteroids screenshotI always wanted to do this and have most of it done. It just needs a bit of polishing plus making it cross-platform. It wasn’t the hardest  thing I’ve done although I did start by trying to make the common part for asteroids, player ship, bullets and aliens, the bit that managed position and velocity into a base class.

I then spent a day wrestling with the compiler trying to access this in those methods that used this and in the end found it easier to make it into its own class and had an instance of it in each of the classes. I.e. using composition rather than inheritance.

Rewriting in C++ made things like saving high scores to disk and reloading a bit simpler using C++ strings.  Now I just have to get my main PC up and running and then polish the code and publish it on GitHub.

 

 

 

Looking at C/C++ extensions for VS Code.

Looking at C/C++ extensions for VS Code.

VS Code C++ extensionsI was curious as to how many C extensions there are for VS Code. If you visit the marketplace (not a great name- all are free-some market!) in a browser, you can search through the (currently) 24,779 available extensions.

Finding C extensions is not easy. A search for C returns almost 16,000 results. C++  is a better thing to search on and gives 207 results, many of which are for C and C++. You can also search in VS Code but it’s easier in a web browser.

Even that’s probably too much but you can use the showing pull down to see how many extensions are in the various categories. If for instance you select Debuggers, then you will only see 18 extensions.

VS Code Extensions showing

Note: As I’m still only my old creaky Ubuntu laptop, I had to use scrot for screen capture and gthumb for editing the image.  Note, the scrot project is looking for a programmer to look after it. Here is how to contribute to the project.

Another Minecraft game in C

Another Minecraft game in C

MinecraftIf you remember back in November I mentioned a Minecraft server that was written in C.  Well now there’s another one that has appeared. Just lIke the other one it uses SDL2 and OpenGL and includes full source code.  This one uses clang.

It’s cross-platform for Windows and Mac and there are two different binaries, one for creative mode and one for survival mode.

It’s still a work in progress and needs sound effects and music, saving and loading levels and multiplayer to complete it. If you are learning C and want to see how a game like this is programmed, download the source code from GitHub and start studying it.

Interesting programming exercise- no loops

Interesting programming exercise- no loops

Recursive fractal
Image by Pete Linforth from Pixabay

I read about a university course where the students had to write C code without using For, While or Goto for loops. Instead they had to use recursion.

Yes it’s bound to be inefficient compared to the looping structure but that’s not the point. For instance for a loop like this:

for (int i=0;i<10;i++) {
   DoSomething(i);
}

It could be done as

void DoSomething(int i) {
   if (i==10) return;
  // Do whatever here
   DoSomething(i+1);
}

DoSomething(0);

The point isn’t to teach you to write inefficient code but to think a bit differently. I’ve used recursion quite extensively in the Slay tutorials code. Here’s an example. It sets a field continent in all adjacent land squares where continent == -1.

void FillIn(int x, int y, int island) {
	if (onMap(x, y)) {
		if (island == map[x][y].island && map[x][y].continent == -1) {
			map[x][y].continent = numContinents;
			allContinents[numContinents].count++;
			FillIn(x - 1, y, island);
			FillIn(x + 1, y, island);
			FillIn(x, y - 1, island);
			FillIn(x, y + 1, island);
			FillIn(x - 1, y - 1, island);
			FillIn(x + 1, y - 1, island);
			FillIn(x + 1, y + 1, island);
			FillIn(x - 1, y + 1, island);
		}
	}
}
So what do I think of C++ compared to C?

So what do I think of C++ compared to C?

Software
Image by Gerd Altmann from Pixabay

I learnt C++ 30 years ago (1991)  and C about 10 years ago.  Mind you I’d had several years of Pascal by then including some OOP (Object Oriented Programming) so it wasn’t that big a thing to learn C++ after Pascal.

For me it’s the objects and the template structures like vect that make the difference. Most C programs that I’ve written don’t really progress beyond using an array of structs. Asteroids, which at 2,200 lines long used a few of those but that was it.

In fact if I wanted any more complicated data structures in C programs, I’d either have to use a 3rd party library or roll my own using pointers.

Programs I’ve written in C# probably use List<Class> more than any other data structure with Dictionary<string,Class> a close second. It really depends upon the type of program you are writing. A lot of mine are reading from a text file or database file, holding data in memory then outputting results.

C++ offers more advanced data structures than C and I spent a fair bit of time rewriting Asteroids replacing all the array of structs as arrays of objects.  Inheritance isn’t that big a thing in OOP but it was handy here because I was able to initially have Asteroids, Space Ships, Bullets and Aliens classes all inherit from a moveable base class. That class had all the code for rotation, movement etc. I found though that C++ could be a real pain when trying to do comparisons between different superclasses and eventually switched from inheritance to composition so those classes had a moveable object instead.

The downside to C++ is remembering if you are copying or moving objects. Not a problem you have in C. One of the interesting problems is how you track the number of active Asteroids which can change from frame to frame. In C I used a fixed array of structs with a field showing whether it was active. Using a vect though and pushing and popping asteroid objects would probably take longer.