Category: Other stuff

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.

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.

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.

 

 

 

An interesting project- Converting BASIC Computer Games

An interesting project- Converting BASIC Computer Games

Basic Computer games bookYes it’s that book again, one I have mentioned a few times.  Now there’s a project to convert all of the games from the book into C#, Java, JavaScript, Python, Ruby and VB.NET. As with all Git sites, you can download all code from the site in a zip file or individual files. So far though its very early in the project and there’s only a .BAS file in each of the subfolders for each of the games in the book. If you fancy getting involved, pick a game, a language and start coding. Sadly there’s no desire for C or C++ but that still leaves C# .

I still have this book and its sequel (More BASIC Computer games!) but to be honest I wouldn’t have bothered with most of the games in either book. They are all very much of the era (1978) which was just on the cusp of the home computer revolution and so were mostly obsolete within seven or eight years, due mainly to the terminal I/O. They’re ok for learning programming and of course you could run them in a Linux terminal.

Learning a programming language is not so easy

Learning a programming language is not so easy

Never stop learning
Image by Gerd Altmann from Pixabay

When I started, back in the dark ages there weren’t many programming languages about. It was a choice of BASIC, Fortran, C, Pascal and Cobol or some obscure languages apl, lisp, snobol etc. At Uni I learnt BASIC in first year then Pascal. We touched on Cobol in one course, enough to put me off it for life. We also did one semester on assembly language for a 6800 CPU. That was fun and probably helped me to learn 6502 and Z80 a few years later.,

Back then once I started learning other languages, it was long before the web existed. Programming languages came with manuals – user guides, reference guides. So you could learn enough to get started and then dip into the reference guide as and when you needed.

But since the Web appeared, the manuals no longer exist as printed books. But what I’ve noticed is, it gets harder to acquire a new technology if you are not working in it fulltime. I learnt PHP and HTML twenty years ago and reinforced that learning by creating websites. But now technologies like Blazor and ASP.NET MVC are quite a bit more complicated.  I’m doing  Udemy course on Blazor with over 200 lessons (most about 5 minutes long) and have only got up to lesson 55. Finding the time is probably one of the hardest things.

C is probably one of the easiest programming languages to learn but any other language or complicated technology is going to take a lot longer. I think It should be easier. There is an immense amount of free material on the web including sites to pose questions (StackOverflow), low cost courses (Udemy), free videos (Youtube) and yet it doesn’t seem easier.  Back pre-web you had to pay for programming languages. But unless you are a student or have a lot of spare time to study, it can be slow learning new stuff.

 

Interesting number sequence

Interesting number sequence

Chess Set
Image by Clker-Free-Vector-Images from Pixabay

Here’s an interesting puzzle (well for some people). If I have the integers 4,5,6,7 and 8 and a special C function f so that f(4)=2, f(5) = 5, f(6)=10, f(7)=40 and f(8) = 92. What is the function f? And no it’s not a simple array containing the numbers 2,5,10,40,92 at positions 4-8!

I also checked the OEIS (Online Encyclopaedia of Integer sequences) and it’s not in there either. Years ago I was fooled by a integer sequence that was the maximum number of electrons in orbital shells but its definitely not that.

Here’s a minor clue. It is game related. Answer in a day or two.

PagedOut a technical programming magazine

PagedOut a technical programming magazine

PagedOut Issue 1 frontcoverIt’s not often that I recommend somebody else but when I see something that I think deserves it, I’m happy to. PagedOut is a free experimental (one article == one page) technical magazine about programming (especially programming tricks!), hacking, security hacking, retro computers, modern computers, electronics, demoscene, and other similar topics. That’s their description! It’s published by Gynvael Coldwind, an IT Security engineer at Google.

It isn’t game related and not totally C oriented. In fact there are currently only two issues out, downloadable as PDFs and the second one has half a dozen C articles but the first issue has none.  There’s a bit of C++, Python, Go and some other stuff including assembly and the content varies enormously and is mostly Linux oriented but there is a bit Windows as well.

The big thing is that each article is just one page long. That’s by design. They accept submissions from anyone, subject to their standards and review but it must fit in one page.

I’ve always had a bit of a hacker mentality going back to when I crashed a mainframe (twice) at University. I didn’t mean to honest….  Being naturally inquisitive I think has helped me as a professional programmer.

 

An uncensored alternative to GitHub

An uncensored alternative to GitHub

Digital cash
Image by WorldSpectrum from Pixabay

I use GitHub a lot, I’ll be the first to admit it but there have been recent cases where GitHub has censored projects because of the US DMCA law ((I’m in the UK so different laws apply here but GitHub is in the US and being owned by Microsoft is not going to ignore the law) so radicle offers a er radical alternative.

It uses Peer to Peer thus avoiding needing servers which can be seized.  People share a bit of their bandwidth and storage and act as anonymous servers; I suspect you don’t see or have any access to stuff stored on your computer. It uses digital cash so those with lot of bandwidth and storage can do more hosting and receive payment from those who are using it.  I’ve seen Ethereum mentioned for 2021 but I think it uses Electron having looked at the community pages.

Slightly ironically, the project is currently hosted on GitHub!  

Am I going to switch to it? Not yet but in the future, who knows?

Could Flash make a comeback?

Could Flash make a comeback?

Ruffle Flash EmulatorBack in the day (2011) I did a bit of Flash game development. It was a curious technology compared to what I was used to. It was originally a way of scripting graphics and other media but really took off when ActionScript, a programming language very much based on JavaScript was introduced.

Unfortunately the twin combination of insecurities in the Flash player’s on PC and refusal by Apple to allow it on iPhones killed it. It took a few years to die and HTML5/JavaScript became a slightly inferior replacement. There were 100s if not thousands of Flash games on websites like Kongregate.com. There are still many games there and on other similar aggregator sites.

But a lot of developers really enjoyed creating Flash games and there have been a few open source emulators. None in C, but at least one in C/C++ and more recently Ruffle (in Rust).  The image is a screenshot from one of the demo games.

What’s different now apart from still not running on mobile is that the “Flash” players are more secure and in this case use WebAssembly for browsers. WebAssembly is seen as the future of browser games and whether it’s by compilin g C/C++ or Rust programs directly into WebAssembly or by using Flash games and animations transformed via programs like Ruffle into WebAssembly, I suspect that the browser will become an increasingly important platform for WebAssembly games.

Talking of which as well as Emscriptem for turning C/C++ with SDL) into WebAssembly there is also Cheerp, an open source and commercial C/C++ compiler that produces WebAssemb;y. I really have no excuse for not producing a WebAssembly version of Asteroids!

Adding an SSL Cert

Adding an SSL Cert

SSL connectionThese days, if you have a website or even a game server then you probably should have an SSL (or TLS to be more precise) certificate. Have you heard of telnet? It’s an old protocol that allows you to connect to a remote computer and issue commands. Do you know why you don’t hear of it any more? Because it was designed for an era where hackers didn’t spend all their time attempting to compromise computers. Telnet, like FTP has a flaw. Passwords and login details are sent in the clear. Not hashed, or encrypted.

Why don’t I use SSH to connect to it? I do. SSH has more functionality than SSL and is very good for encrypting remote connections. SSL needs a certificate, whereas SSH doesn’t but many think you should use a SSH certificate as a substitute for username/password and I intend to. If you’re not sure of the technical differences between SSL and SSH, this article isn’t a bad place.

So today I paid for an SSL certificate. I’d pointed a domain I had handy to the vps a few days ago, to give DNS a chance to settle, (24 hours max but usually much less) paid £20 for five years of SSL cert and installed it today. Thankfully, virtualmin which I use for configuring the server makes it straightforward to request a SSL by generating the CSR (Certificate Request an Private Key) . This blog uses an SSL cert from the same place (CheapSSL). Despite the low price the certificates are very good.

Although the world won’t see what the cert is protecting, you almost have to have them nowadays. This is for the connection between smartphone and server. As I found today, Apple is ramping up security and Google is doing the same. I have iOS 14 on my iPhone (upgraded yesterday) and it refused to connect to WiFi in my local coffeeshop. Their certificate doesn’t expire for another month but I suspect it is now over 398 days old. As far as Apple is concerned, that certificate is past its use by date. This is Apple’s new policy since earlier this year. My wife’s iPhone, still on iOS 13 connected quite happily.

For those who have bought a multi-year certificate as I have today, it just means you have to generate another CSR and install a newer certificate once every 400 days or so. I’ve started taking screenshots of the details so I get them correct! I believe Google is moving to this 398 day maximum as well.

So the commands from smartphone to game server are now sent over https and encrypted in flight as are the results. It’s one less thing to worry about.