Discussing the use of break in C

Discussing the use of break in C

C
Image by pramit marattha from Pixabay

On the C programming subreddit there’s a discussion where a student has been old he should never use break in C. As one comment says, “The teacher is a nitwit” and I agree with that comment.

I use break (a) to exit loops early and (b) to exit every branch of a switch statement unless I want it to drop through or else that case does a return. I use switch a few times in the asteroids source code and there’s examples of all three instances of using breaks, using returns and dropping through cases (no break).

Here’s an example of the latter. It controls the logic of what to display when you start or restart a level after losing lose a life. If you have one life left it prints “Last life” otherwise it prints how many you’ve got. Actually I think it’s a bit of an overkill and an if else would have done just as well

 

	switch (Player.lives) {
		case 1:sprintf_s(buffer, sizeof(buffer), "Last Life!");
			break;
		case 2:
		case 3:sprintf_s(buffer, sizeof(buffer), "Lives left: %d", Player.lives);
			break;
		}

So probably not the best example of using a switch! But it illustrates a point.

A comprehensive small C compiler

A comprehensive small C compiler

Programming image
Image by Gerd Altmann from Pixabay

Once you’ve learnt a fair bit of C, one way to increase your understanding of it is to see how a C compiler works. Unlike most other programming languages, C compilers are generally understandable. There have been a few tiny or small C compilers around and here is another one though as its C111 compatible, it might be more useful than older ones.

The author is well qualified to write this, he’s the author of the llvm lld linker and also an earlier C compiler 8CC. He notes “chibicc can compile several real-world programs, including GitSQLite and libpng, without making modifications to the compiled programs. Generated executables of these programs pass their corresponding test suites.”

Rui is writing a book on the C compiler and this is the subject of the book. It’s not out yet but will be in my must buy list.

Don’t create a game with Ville in the name

Don’t create a game with Ville in the name

A ville
Image by Pete Linforth from Pixabay

Well not if you live in the EU. I came up with Glitzville back in 2002. It doesn’t sound too bad. However, if you do a search of the European Trade mark database for the word Ville, you’ll find EU009774613 a trademark on the word Ville in three classes of trademarks. Classes 9 and 41 between them cover virtually any use in software, games, electronic devices and online. While class 25 covers t-shirts and other items of clothing.

The long and the short of it, if you live in Europe and want to sell a game that ends in ville or even do t-shirts and other merchandise, forget it; you’ll likely get sued thanks to Zynga, creator of games like FarmVille etc.

I had registered the domain years before 2011 the year when this trademark was taken out. I wasn’t the first to use it, as back in 2004, in the game Paper Mario there’s a city of that name. See Glitzville but it didn’t become a problem until Zynga came along. So  has Zynga ever sued anybody? Most certainly, for instance here’s a case from 2012.

For most small publishers, the chances are that your game/app name will not get you into legal trouble but it’s probably worth a bit of checking just in case. And trademark violations (unlike copyright ) have some seriously big fines with them- possibly tens of (£)thousands.

Actually going schemaless in C#

Actually going schemaless in C#

JSON Image
Image from json.org

Back in August I talked about going schemaless and I’ve made some progress since then. I’ve created a number of C# classes, many of which include single and in one cases a 2D array of things I want persisted to disk.

I use JSON (JavaScript Object Notation) files to hold the data.  So long as I’ve defined those classes with Properties using Get and Set, the JSON converters in .NET handles it all very nicely.

For example, in my game I have a CityArea class which includes a List<BuildingType> as well as several public properties.

This saved out as JSON like this:

[
  [
    {
      "buildings": [
        {
          "Name": "College",
          "Size": 2,
          "Percent": 60,
          "Cost": 50,
          "Type": 11
        },
        {
          "Name": "Gallery",
          "Size": 2,
          "Percent": 40,
          "Cost": 150,
          "Type": 23
        },
and ends...
      ],
      "State": "R",
      "Type": "F",
      "Density": "L",
      "Points": 46,
      "AreaName": "Newfane"
    },

The whole JSON file has 1500 buildings scattered amongst 100 areas (10 x 10) and is 11422 lines long. The file is 234Kb long. Though that’s with indentations. I could remove that but for now, during development, it makes the file easier to read.

These are the two class definitions (I’ve removed extraneous stuff from them),

class BuildingType : ICloneable {
        public string Name { get; set; } = "";
        public BuildingSize Size { get; set; } = BuildingSize.bsNone;
        public int Percent { get; set; }
        public int Cost { get; set; }
        public BuildType Type { get; set; }
}

class CityArea {
        public char State { get; set; }
        public char Type { get; set; }
        public char Density { get; set; }
        public int Points { get; set; }
        public string AreaName { get; set; }
        public static List AllBuildings = new List();		
}

This is the code to save out areas (which is List<CityArea> areas to the file. I found this by reading the Microsoft documentation about Serialization and deserialization. It’s pretty good stuff and the code for saving these structures are these pretty short methods.

        public bool SaveToUTF8(string filename)
        {
            var options = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            var bytes = JsonSerializer.SerializeToUtf8Bytes(areas, options);
            File.WriteAllBytes(filename, bytes);
            return true;
        }

and this is the code to Load it.

        public bool Load(string filename)
        {
            try
            {
                var bytes = File.ReadAllText(filename);
                areas = JsonSerializer.Deserialize<CityArea[][]>(bytes);
            }catch(Exception e)
            {
                Error = $"Failed to load {filename} because {e.Message}";
                return false;
            }
            return true;
        }

I haven’t timed either Load or Save but they are fractions of a second.

Fascinating look at the BBC Micro game Elite

Fascinating look at the BBC Micro game Elite

BBC Micro EditeThis is somewhat off-topic and a little bit of self-indulgence because (a) it’s about a computer that existed over 36 years ago and (b) a game that was programmed in 6502 assembler. It’s also a game I played a lot back in 1984.

The reason for including it here is because a British Web Developer called Mark Moxon has created an excellent website about the game, looking at the algorithms, source code etc. of the BBC Micro version of Elite. Everything you wanted to know about how it works.

I’d sum up this website as the “Cliff’s Notes” to the BBC Micro version of Elite. Be sure to click the three bars at the top left as the Navigation Bar gives an idea of just how much there is in this website. There’s bit by bit breakdowns of variables for example, in generating System Data.

Government
  ----------
  The government is given by a 3-bit value, taken from bits 3-5 of w1_lo. This
  value determine the type of government as follows:
  
    0 = Anarchy
    1 = Feudal
    2 = Multi-government
    3 = Dictatorship
    4 = Communist
    5 = Confederacy
    6 = Democracy
    7 = Corporate State

This is a remarkable piece of work, I can’t imagine how many hours Mark has put into it. Possibly as many as it took to develop the game originally!

Where do I get a lot of my information from?

Where do I get a lot of my information from?

SubredditsI was asked this a few months ago. There are various sources including Hackers News and Reddit.com. But reddit is just a collection of specialised sub communities (known as Subreddits) and even I wasn’t aware of quite how many there are.

I came across a link which lists 43 programming related subreddits. On the right hand bar there’ a list of a few Subreddits but at the bottom there’s a View More link to show all 43.

I’ve shown them here to give you an idea of what’s available. The member numbers will change and are often out of date anyway.

Tutorial 3 on Enum variables published

Tutorial 3 on Enum variables published

Magic Numbers
Image by John Hain from Pixabay

This is the third in a series of C Tutorials that I originally published on about.com between 2006 and 2013.  I’m republishing them on here. This time it’s about enum variables. While these aren’t anywhere as important as say in C++ or other languages (because C’s type checking is not great!) they make the program more readable.

I see them as banishing magic numbers. A magic number is a number in a program that is just there. Like when you declare an array and use the number 20. That is a magic number and it would be better if there was a #define NUMBERMONSTERS 20.  This avoids the problem of your program being full of 20s until one day you change it to 30 but manage to miss a couple of them and you introduce bugs. By using NUMBERMONSTERS everywhere you can change it in just one place (at the #define) and avoid the problem of missing.

Enum variables are similar. Behind the scenes they are just ints. In other programming languages like C++, Pascal, C#, the compiler enforces the enum values. In those languages you can’t declare an enum variable then assign any int value to it, but in C you can.  But they can at least make your program more readable.

The picture? Magic numbers!

To brace or not to brace

To brace or not to brace

Abstract programming picture
Image by Gerd Altmann from Pixabay

This isn’t exactly confined to C, in fact it applies to many programming languages where braces or curly brackets {like this} are optional after an if. It even applies to Pascal with Begin ends which are optional after an if.

You can have the first or the second as shown below.

if (expressions) 
  DoSomething;

if (expression {
  DoSomething;
}

I saw a recent example where the DoSomething was a logging expression which the compiler optimised away so the if, which lacked braces applied to the next statement. As the if was only true on rare occasions. It meant that that statement which should have been run every time was only run on those rare occasions.

So the prevailing wisdom and one that I entirely agree with is that you should always use braces. If you don’t you risk accidentally introducing bugs like this.

Note. that link is to a discussion on the C programming Subreddit (on Reddit.com).

.

A lovely MiniGolf game in C

A lovely MiniGolf game in C

MiniGolfA developer called Michael Gerdes just published a MiniGolf game on GitHub. This uses OpenGL for the graphiocs and according to GitHub is made up of

  • C 76.5%
  • C++21.4%
  • GLSL 0.8%
  • Scheme 0.7%
  • Objective-C 0.6%
  • HTML 0.0%

Every project on GitHub has these on the RHS of the home page. They include links with filters to see the particular set of files. Particularly telling is GLSL which are shaders. If you do 3D graphics, that’s something you need to learn. Its why I stick to 2D. The other stuff probably comes as part of various linked libraries.

It’s nicely done and the GitHub page has four animated gifs showing how it works. It also uses the open source Dear Imgui GUI library.