Learning the C Programming Language as a Classical Musician

Episode 2

Welcome back!

In the last episode we looked at the motivations behind this new delving into the world of programming, why I decided to start with the C Programming Language, and how to create your first C project on macOS 12.x using Xcode 13.x. Today we will analyse the structure of a C project created on the Mac and review some basic concepts of the language. Let’s get started!

A Command Line Tool

To write C code on the Mac using the latest available IDE (Interactive Development Environment), currently Xcode 13.2, we need to create a new project using the Command Line Tool template, which is hosted under the macOS category. You may also create an empty project, add an empty file, or a C file, and work your way from there but, sometimes, it is good to have a solid ground under our feet.

If you have followed the steps in the previous episode, you should now have an open Xcode project window in front of you.

Xcode’s window comprises three main parts: to the left we have the Navigators, to the right the Inspectors, and in the center the main area which can change name according to what you are doing it, but is normally referred to as the Editor area. The active navigator upon opening the project should be the Project navigator, here highlighted in orange, as that is my macOS tint colour of choice. Another area will expand from below when we build and run our program and is called the Debug area, as that is where the results of the program will be shown.

This organisation is akin to what a composer of a musical piece would need before starting to actually jot down the notes on paper. I see many connections here because planning seems to be key in an interdisciplinary way. Here, in Xcode, we lay down the structure of our code (app, command-line tool, game, …), then we develop from each tree branch and, if necessary, we add in some customisation from the inspectors to the right, which, by the way, changes appearance contextually according to what you are doing. In music, the composer would start with the structure of the piece (a symphony, a chamber work, a solo piece), adding details such as instrumentation, key, or tonality with planned modulations, metric structure and everything else that would come to their mind before starting the actual creation process. Then, they would “select” a piece of the structure and kickstart the creative process, seldom from beginning to end, but writing melodies, isolated harmonies, then combining them together as a painter would do with their palette. During this process, some fine-tuning would be needed, such as adding an articulation (staccato, tenuto, marcato, …) or a dynamic (forte, piano, sforzato), for which the Inspector would be the closest comparison. Eventually, a tentative listening would be needed, either by the composer at the piano, or by a Digital Audio Workstation (DAW) such as Logic or Cubase. At this point, the composer’s debug area would pop up and let them hear what would need improvement.

This navigator shows the structure of the project and starts with an App Store-like icon at the top, which is known as the Project Icon, while the folder just below it is known as a Group, as you can “group” several files inside it. The Editor area contains a lot of potentially interesting information, but we will skip them for now as they are not crucial.

Inside the “Learning C Ep1” group we have a single file called main.c. The .c file extension tells us that it is a file using the C language while the main name is a requirement for all C files as the compiler will run every instruction you throw at it only if it is inside the main function, which we will look at shortly.

Now, select the main.c file to open it in the Editor area. This is what you should see onscreen:

In many programming languages, the double forward slash // is an introduction to a comment, which is something you may want to say about your code. The compiler will ignore it and the IDE is helping us recognise it by giving it this grey colour (though you can change it to whatever colour you wish in Xcode’s Preferences). The first 6 lines of code are just comments, and they contain the name of the file on line 2, the name of the project on line 3, the creator and the date of creation on line 5. That is akin to what a composer would write on the first page of the manuscript, for example: “Allegro moderato”, then “Sonata for violin and piano in C-sharp minor”, and finally, their name and the date of start of the manuscript.

Line 8 is pretty interesting and vital to the functioning of a C file:

#include <stdio.h>

The “pound include” asks the compiler to import the functionalities offered by a special kind of file called “header” (yes, like the header of a page) into our program. It is like a title of a box containing things that help our program run. To avoid technicalities, you can refer to this Wikipedia article about directives. After this directive, we can have angled brackets (<>) or double quotes (“”) around the name of a file. If we have angled brackets the file is something included with the IDE or, better, with the operative system itself, while if we have the double quotes the file has been created by us, and we will see how to do just that in a future episode. The stdio.h file name stands for “Standard Input and Output” (the .h stands for header file) and regulates the how and what can be done in our program in matters of getting input from outside and printing output to the console. Then, we have this beauty:

int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n");
    return 0;
}

Let me introduce you to the main function, the core of our C program. After studying Swift for two years and then coming back to the basics, I find this so much more natural—I know, it’s personal. The int at the beginning occupies the place of the return type of our function, that is, what kind of data will our function send to the console. If you look at the end of the function, you will see return 0; which is a story of its own. I am sure you have encountered the “Error 404” on a webpage countless times in your browsing life: well, that is precisely the webpage’s rendering function (not necessarily written in C) returning 404 instead of 0. In programming history, having a program exiting with 0 meant that everything had gone well, or at least that the program had not crashed, fallen into an infinite loop, etc … For big programs, safety practices suggested having the program return a different number for each kind of error that was possible, giving then a massive manual of error codes to help technicians solve those issues. I have forgotten to tell you what int is, but I am sure you have already guessed it right: it is an integer number such as 0, 42, -30, ….

Next to the return type we have the function name, main, followed by some obscure looking text enclosed in parentheses. In C, a function needs to follow this basic format:

<returnType> <functionName>(<optionalParameter>)

This means that we do not need to have anything inside those parentheses but that, in this case, we do. What is a parameter? It is something that you “pass” to your function to modify its behaviour. For example, you want to create a function that calculates the compound meter equivalent of a simple meter? You could certainly create a different function for every single simple meter available to all musical cultures and traditions, but why not optimise the process? Write a couple of parameters that accept integers for beats and values, and then pass those values in when you call that function. This very example is harder than it seems because there is no “fraction” type in C (nor in any other programming language I have seen) but still, it would work.

void makeCompoundOf(int beats, int value) {
    printf("The compound time of %d/%d is %d/%d\n", beats, value, beats * 3, value * 2);
}

int main(int argc, const char * argv[]) {
    makeCompoundOf(2, 4);
    return 0;
}

This would print the following to the console:

The compound time of 2/4 is 6/8
Program ended with exit code: 0

Which is just great! Don’t worry if you do not understand everything in there, we will get there!

When you call your function, you pass in arguments where the function asks you to complete its parameters (thus the 2 and 4 inside my new main function in the makeCoumpoundOf() call are actually arguments). In short, parameters and arguments are kind of the same thing, just the first is the internal name to be used inside the function, while the second is the external name to be used in separate calls the function.

The parameters used by the main function are a hard topic and will be discussed much later.

The final thing we have to look at it the printf call inside the main function. As said, it is a function that, in theory, returns an int, and this because, for a computer, everything starts as an integer (0, 1 in binary code). It accepts a string of characters (which is the text you see inside the double quotes), some other data and converts it to be written to the specified output. In practice, it is everything much more complex than this, but we do not need to get that deep this soon.

What’s next

In the next episode we will look at some basic concepts and terminology of the C programming language as, during my learning journey, I found that I was missing the understanding of those basics to move on serenely.

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

One thought 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: