Wednesday, July 24, 2019

The Last “Hello World” You will need

Entering the world of C++

Saying Hello World in more ways than one

Hello World! In this post, I wanted to begin my exploration of c++ and beyond by first unwrapping
one of the most well written topics in computer programming. That is, I want to contribute to the
plethora of Hello World tutorials that exist out there. This time however, we are going to write Hello World in a number of different ways. If you can think of another way, go ahead and post it in the comment section below.

Here we assume that you have your C++ environment all together. If you don't here are some other
fine tutorials to get you fired up.
[linux], [windows], [mac]

The Bread and Butter

First we are going to write Hello World in whats considered the defacto way in modern C++.
If you are ever wondering how you should write your hello world program, this
should be your first choice. It looks like this.

There it is in all its glory. Looking at those lines of code is like seeing an old friend, you can’t help but say hello back. Breaking it down, the first line introduces the C++ standard input output file stream library. This makes the input and output facilities available in our program. Next line lets the compiler know that we are using the namespace ‘std’ throughout this source file. Without this line, we would have to add “std::” in front of all standard library members such as “std::cout” instead of just “cout” as you see later on in the code.

The next block of code is where the magic happens. “int main()” defines a function called main that returns an integer. In c++, main is a special function name. When running a C++ project, the computer (really the runtime) looks for a function named “main” as the starting point of execution. Following this, we then output “Hello World” to the console by using our “cout” function from the iostream standard library. We place the “endl” at the end to create a newline. 

We will talk about “endl” in more detail in the future.

The “return” produces the value that main will return once it runs this line. This main returns 0 as a result.

Nice, that's a complete Hello World for you. But lets see other ways we can achieve this program.

Hello World like it’s 1999

C++, getting its roots from C, also has some other functions that allow one to output to the console. These functions, born in C can be very useful as well. Let’s take a look once more at a Hello World program but this time we are going to say "Hello World" a number of times. Why? Just because we can.

I'm sure you are thinking “wait, what?”. But check this out. We import our library first, this time using the C-style input output library. Then we introduce our main function once again. This is followed by our second way of getting our text to console, the “printf()” function. In this instance, it completes the same job as that of our “cout” example. Resulting in “Hello World” being produced. The “\n” how a new line character is represented.

After this, we start getting into some interesting, yet onerous approaches to hello world. You probably won’t be writing the program like this but it does offer a deeper understanding into this function. After our first “printf” line, we use “printf” once again. This time we start with a string that has a ‘%s’. This uses printf’s formatting functionality which will replace‘%s’ with any string we provide. In this case the next argument which is our “Hello World\n”. This prints to the console what you would expect, replacing ‘%s’ with our hello world string.

The next two “printf”s once again utilize the string formatting offered by printf. In this case the ‘%c’ lets use replace it with a single ascii character. The third “printf”, places a series of ‘%c’, one for each character in “Hello World\n”. Note that ‘\n’ is treated as a single character. Following this formatted string, we have a comma separated list of each character to replace each ‘%c’ in this string as they appear. Thus replacing each ‘%c’ with the characters of “Hello World”. Up next we have a similar “printf” function with the same series of ‘%c’ but this time we represent each character as its equivalent digit. In C++ each char can be represented as an unsigned integer. Looking at an ASCII table you can see which integer corresponds to which character. Telling the function to look at those numbers as characters using the ‘%c’ we once again get our “Hello World”.

There you have it, “printf” in all its Hello World glory. But if you think we are done with our Back 2 the Future experience you can guess again. Let’s look at our third approach to Hello World.

Our third method of getting text to the terminal is using “puts” function call. This takes a c-style string as input and prints it to console. C-style means a char pointer to a null terminate sequence of characters. Above, I use two ways to create this c-style string. First we declare a const character pointer and assign it a string literal. In modern C++, you are required to declare a char pointer constant when assigning a string literal to it - one of the attempts made to make C++ safer with less pitfalls. Next, we declare an array of char’s and assign it the string. This creates an area with each character in each array cell.

We are breezing over a number of C++ concepts like arrays and pointers but we will cover those in the future so stay tuned.

We then pass those strings to the “puts” function which as you know outputs the string to the console. Like the comment says, the line starting from the “//” onward, “puts” adds a newline at the end of its output which is great for us. Looking at all the examples above, we can see all the main print to console functionality offered by C++ out of the box. As we mentioned before, your first instincts should be to reach for the std::cout function call. But these other two functions are available when the situation calls.

With these tools at hand, why not have a little fun. Let's write two more Hello World programs but let's spice things up a little more.

Sharing the Workload
These next examples bring in more complex topics into the picture. We will be touching on them briefly but it gives you an idea of some cool C++ libraries available.

Now, it's great having our main function do the work of printing to console. But, what if we want to get another execution thread to take care of this work for us? Why would we want to do that? There are many reasons that may perhaps exist. But for our hello world, we are doing it for the joy in seeing “parallel” code.

“What in the world is going on here” might be your thought. Let me explain, off the bat we use new standard library functionality, which is the std::thread api. This allows us to create a second thread of execution that can run separately from our main thread of execution. Think of this as hiring a new intern to work with you. Now you and the intern can work together at the same time.
Next we see some interesting syntax. "[]{...}", allows us to declare an anonymous function which is a function with no name. Remember, main() is our other function that we know of. The only line of code in our anonymous function is the Hello World as we have seen before. Together, this creates a new thread object and passes in, as input, the lines of instructions that the thread will begin to execute immediately once created.

The following line, is an if statement where we check whether our thread can be joined. In other words, we check if the thread has neither finished running nor been explicitly detached from our main thread. If the thread is joinable, we join our main thread to it. This makes our main thread wait until our second thread completes running before moving from that join point.
Again, some new concepts here but at the very least we have named some new topics to explore on our C++ journey.
What happens when we want to employ more than one thread in our Hello World experience. One might say, “we really should not”. I say, “more threads please!”. Let’s do it.

Yep, this is our most contrived example of a Hello World. Lots of cool concepts abound here. Our goal here is to have two new threads write "Hello World" one after the other. Considering these threads begin execution right after being created, we need to synchronize their activity. Here is where we introduce a mutex and a conditional_variable. Together they let us create checks and balances that must be met before a thread can execute code. We are going to walk this code in finer detail in a different post but for now, understand that the usage of the mutex library and the conditional_variable library allows us to coordinate the actions of our threads. Thus, allowing control of when thread one prints “Hello” and when thread two prints “World”.
What more detail, dive in here.

What a journey, we have seen how to use C++ standard library to print to the console and we even dipped our toes into the standard threads library to achieve the same thing. Alongside learning more about C++, its syntax and libraries, this is an example really about simple ways to play with a language and learn/practice something new. Hope you all find this useful and insightful. Let me know if there are any particular topics you are interested in me covering below. If you just have comments to share please do the same below.

What are you waiting for, get coding!