Category: C

Another maze generator and solver in C

Another maze generator and solver in C

Solved mazeI liked this one; it compiled perfectly without any changes and ran perfectly. It produces a maze of the specified size with a route. That’s not bad for a program written over 20 years ago. By developer Joe Wingbermuehle. You can view the source code here.

It runs in a terminal, just supply width and height characters like this. I compiled it into a file ex1.

./ex1 15 15 s

If you provide the s parameter, it will solve it as the screenshot shows using <> for the solved route. off for just the maze.

How to encrypt text using Xor

How to encrypt text using Xor

Binary
Image by Gerd Altmann from Pixabay

This is not meant to offer protection, but if you want to say hide text by disguising it, then using Xor for reversible encryption will do the trick. It relies on the principle that if you Xor A and B to get C then you can Xor C and A to get B or Xor C and B to get A.

I wrote a short program and tutorials to demonstrate taking a single bit of text then disguising it. To make it more challenging, I only used Xor values from the range 0-255 that had four or more bits with 1 in it, for example 15 which is 00001111 in binary.

You can find the tutorial How to do Xor encryption in C. Please note this is only a very light weight encryption method so don’t use it for anything too important!

How to extend C (99) with a library

How to extend C (99) with a library

toolkitI’m always looking to improve my C code and one way to do this is through others efforts. Today I came across Zpl, a cross-platform header-only library.

The zpl.h file is a whopping 17,495 lines long!  It has code for macro helpers,  memory, collections, string, hashtable, file, memory streamer, print, time, random, sorting and miscellaneous.

Given the length, it would be difficult to make sense but the authors (Vladyslav Hrytsenko and Dominik Madarász from the Ukraine and Slovakia respectively) have provided a folder of example applications that use the library.

It looks a very impressive library and well worth a look.

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
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.

Core War in C

Core War in C

Core WarCore war is an old game concept that dates back to 1984. If you imagine a simple CPU with small programs written in assembly language trying to wipe each other out, that’s Core War and you can read about it in a lot more detail on Wikipedia.

Inevitably for a game of that vintage there is a C implementation on GitHub by developer Emil Wallner. There’s an animated version of the screenshot showing the game play in action.

The programs (representing viruses) are small assembly language programs that move themselves around the virtual memory and duplicate themselves and try to wipe out the opposition. I’ll always meant to write one of these myself but for now there’s this.