0x4e57

Prelude to C: Static type checking

08-31-21

This is the first in a series of posts to explain a couple of important concepts prior to diving into C. My hope is that it will make things a little easier to understand when we get into the syntax of the language.

What is static type checking?

Static type checking is a way to verify the correctness of a program.

For example, if I try to calculate "3" + 5 in python I’ll get this error:

TypeError: can only concatenate str (not "int") to str

That’s python’s type checker telling us our program is incorrect. And that makese sense because trying to add "3" + 5 is like trying to answer the question:

What is the sum of the word "apple" and 74?

It’s nonsense.

Languages that do this type of thing are referred to as “strongly typed”.

The opposite of strongly typed? Weakly typed.

Javascript is an example of a weekly typed language. If you open up your browser console and type "apple" + 74 you’ll get an answer of “apple74”.

Javascript doesn’t care that we’re adding a word to a number.

This is why you probably don’t want to build financial software with javascript.

Type checking in C compared to Python

Now that we’ve defined the terms, let’s compare a python function and C function within the context of static type checking.

Python:

def add(a, b):
    return a + b

If you were to use the python function in a script, you could do the following:

sum = add("apple", 74)

In python this is considered valid code until it runs. In other words, as soon as the program tries to add “apple” to 74, it will blow up. This is referred to as a “runtime error”.

C:

int add(int a, int b) {
    return a + b;
}

The first int states that the function add will return a number.

The second int states that the variable a is a number;

The third int states that the variable b is a number;

Now, say we tried to use the C function and we wrote the following C code:

int sum = add("apple", 74);

When we tried to compile our program we would get an error stating that our program is incorrect. This is referred to as a “compile time error”.

Compile time vs Runtime

If you goal is to build robust software, the difference between compile time type checking and runtime type checking is important.

With compile time type checking the compiler gives you information about the correctness - or incorrectness - of your code before you deliver it to the customer.

With runtime type checking you only get feedback when the program runs. Ideally, this would happen during development, when running the program on some dev machine. In practice, it’s likely the customer will find it.

And that’s one of the primary reasons the dynamic language communities write so many tests for their code. They’re trying to recreate the compile time protection of languages like C.

Anyway, that’s the gist of static type checking.

Later!