Learning the C Programming Language as a Classical Musician

Episode 4

Welcome back and thank you for sticking with me!

In this episode, we will scratch the surface of what programming is, learn how to comment your code, and what your computer is doing when compiling your code. I will try to add as many music-related examples as possible but, in these first stages, it is not always easy.

Let’s get started!

Comments

Not all what we write in our programs is actual code. Every so often, we need to add a note about what this code is actually doing. This is useful, not much at the moment, but for when you will review your code in the future, or give it to somebody else to read. Modern programming languages like Swift have become simple to predict but, at times, a block of code can be very long and having an idea of what that code is (or should be) doing beforehand is indeed useful. Here is where comments come to the rescue. They serve as a sort of documentation inside your code and are always ignored by the compiler. In short, they are aimed at humans. These are akin to when, in music, you make a sketch to the side of the score which is not going to affect the notes themselves, rather their performance, or the way the conductor is going to approach your piece.

There are two main types of comments: C-style and C++-style comments (the second read “C plus plus style”, not “C plus plus minus style”, though confusing as it can be), with a few bonus ones included by Xcode.

A C-style comment is also known as “multi-line” comment and is created by a forward-slash and an asterisk /*. Anything after these two characters will not be compiled so, to end the comment, just write */, that is, the mirror of what you wrote before.

/* this is a "C-style" comment
 and it can span multiple lines
 */ 

A C++-style comment, also known as “single-line” comment, is created by a double forward slash // and does not need to be closed as just hitting the Return key will perform the deed.

// this is a "C++-style" comment
// To keep commenting on a new line I need to insert // again

It is immediately clear that a C-style comment is more apt to comment out large blocks of text or small fragments of code; they can be used for single lines, but the C++-style is better for this. The /* and */ characters will not be considered part of the commenting process if inside a character constant or a string literal, in short, when the definition of an object is something like this:

const char a = '/*'; // this is a character constant
char *b = "b ignores /* */"; // this is a string literal

Xcode special comments

In Xcode, we have access to other kinds of comments, which help us give our code a better structure. The first one is the “MARK” comment, which makes the text of the comment appear in the navigation outline that sits above the Editor Area.

You add it by typing // MARK: followed by the text you want to show in the navigation outline. In my case:

// MARK: Comments

This can go one step further as if you add a dash - after the column, so // MARK: -, it will also add a horizontal line above the text, to make the category separation clearer. Just do not overuse it.

This was created by typing, inside the main function—that’s why it is indented—, // MARK: - New section. You can even just create a separator line with // MARK: - (I normally add a space after the column, but it is not necessary).

If you have found a bug in your code, but you cannot fix it immediately, just add a “Fix me” comment, which is done by using this syntax // FIXME: followed by the text you want to stand out. This makes a kind of bandage icon appear in the outline so that it is clearly visible. You can also add a #warning("Some text to make this stand out") in case you forget about it.

Finally, you can add yourself a “To-do” comment using, you name it, the // TODO: syntax. You can see how the icon is now a checklist. Adding a dash after the column for the Fix me and To-do comments simply adds it to the outline, not inside your code as the Mark comment does.

We could talk here more about how to document your code “the official way” in Xcode, but I will leave it out for now as it is not directly related to C. I will dedicate a separate episode to this in the future.

ASCII

One of the most fascinating things in computing for me is that, in the end, everything is a number! I mentioned in a previous episode how the computer cannot distinguish an a from a b, but only a 1 from a 2, and normally not even that because we need to convert it in binary code. So, humans needed to define a standard to make communication between man and machine possible when using text or numbers. The story is much longer and more interesting than this, but at some point during the 1960s, the ASCII (American Standard Code for Information Interchange) standard was born.

It is classified using decimal, octal, or hexadecimal numbers, and classifies the basic characters in a table from 0 to 127 (included in a single byte, which is 8-bit long). So, for example, when you type Spacebar on your keyboard, the computer gets 32! Isn’t it fascinating? Numbers, that is, digits, from 0 to 9 are reserved slots 48 to 57. What about characters? Capital a (A) is 65, while lowercase a is 97. Playing with these is such a load of fun that I couldn’t help it:

printf("%c\n", 65);

The %c is a placeholder known as conversion specifier, and there are quite a few of them, in this case it holds a single character. The printf call is a function that accepts an indefinite number of arguments—known as a variadic function—. The 65 after the comma is the integer we pass to the conversion specifier. But wait, we pass an integer to a character? Yes, because that is what a character is in the end. The console, when you run the code, will happily write A! Now for a more complex example:

puts("Printable ASCII:");
for (int i = 32; i < 127; i++) {
    putchar(i);
	putchar(i % 16 == 15 ? '\n' : ' ');
}

The puts function is very similar to the printf one, just that it accepts only one argument and automatically adds \n (which gives us a newline) at the end. putchar accepts only a character and doesn’t add a newline terminator. The output for this will be:

Printable ASCII:
  ! " # $ % & ' ( ) * + , - . /
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@ A B C D E F G H I J K L M N O
P Q R S T U V W X Y Z [ \ ] ^ _
` a b c d e f g h i j k l m n o
p q r s t u v w x y z { | } ~

How did we get this? The first line is the result of the puts call. The loop defines an integer i equal to 32, sets itself to run as long as i is less than 127, and adds 1 to i after each loop (that’s what the i++ does). In every loop, it will “print” the character associated with i (you see the advantage? We do not have to use printf every time with a %c conversion specifier), then, and this is the nice part, we have the second line, which contains two new concepts, the modulo operator and the ternary conditional operator. The modulo is used in ordinary math and means “give me the remainder of this operation”, so i % 16 means “give me whatever the remainder of i divided by 16 is”. The ternary conditional operator works in this way: if the statement before == is true, perform the action that follows the question mark ?, otherwise perform the operation that follows the column :. So, in this case, it should read: “if the remainder of i divided by 16 is equal to 15, add a newline terminator \n, otherwise, just add a space”. This is what makes it so nicely formatted!

I encourage you to play wildly with this, as it is beyond funny!

What’s next?

Once more, I have promised more content than it could fit in this article, so I will continue in the next episode with what happens when your code is compiled. We may look at other things, but I want to avoid promising what I cannot keep. I would like these articles to be a 5-minutes read, but so far, I have always exceeded it. I still hope you are enjoying them!

Bottom Line

Thank you for reading today’s article.

If you have any question or suggestion, please leave a comment below or contact me using the dedicated contact form. Assuming you do not already do so, please subscribe to my newsletter on Gumroad, to receive exclusive discounts and free products.

I hope you found this article helpful, if you did, please like it and share it with your friends and peers. Don’t forget to follow me on this blog and to let me know what you think.

If you are interested in my music engraving services and publications don’t forget to visit my Facebook page and the pages where I publish my scores (Gumroad, SheetMusicPlus, ScoreExchange and on Apple Books).

You can also support me by buying Paul Hudson’s Swift programming books from this Affiliate Link or BigMountainStudio’s books from this Affiliate Link.

Thank you so much for reading!

Until the next one, this is Michele, the Music Designer.

Published by Michele Galvagno

Professional Musical Scores Designer and Engraver Graduated Classical Musician (cello) and Teacher Tech Enthusiast and Apprentice iOS / macOS Developer Grafico di Partiture Musicali Professionista Musicista classico diplomato (violoncello) ed insegnante Appassionato di tecnologia ed apprendista Sviluppatore iOS / macOS

2 thoughts on “Learning the C Programming Language as a Classical Musician

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: