C++ simple example

I’m beginning to read the glorious: The C++ Programming Language, 4 ed., by Bjarne Stroustrup.

I’m okay saying I have no knowledge at all about C++. I’ve been avoiding it ever since I started college, but I feel compelled to give it a try. Not just because I feel like it but it’s one of the most used programming languages and it’s needed to learn Vulkan (wich interests me), the succesor of OpenGL.

It looks hard, but I guess time will prove. I remember C looked impossible 3 years ago, now it’s just another language. (Nevermind my journey with Ocaml).

Let’s jump right into it!

Always remember that the C++ compiler reads C code without any trouble. So we just have to add concepts and know C.

I think a comparison will do to show some light concepts that are new in C++.

How would you create an array of integers, of a size determined at run-time, and then fill it?

In c we would just do this:

 1 /* example1.c */
 2 #include <stdio.h>
 3 #include <stdlib.h>
 5 int main(void)
 6 {
 7     uint size = 0;
 8     scanf("%u", &size);
10     int arr[size];
11     uint i;
12     for (i = 0; i < size; ++i)
13     {
14         scanf("%d", &arr[i]);
15     }
16     return 0;
17 }

Simple enough, and in c++:

 1 /* example1.cpp */
 2 #include <iostream>
 4 int main(void)
 5 {
 6     uint size {0};
 7     std::cin >> size;
 9     int arr[size];
10     for (auto& x : arr)
11     {
12         std::cin >> x;
13     }
14     return 0;
15 }

As I said, C++ and C are totally related. Each line has been “translated”, the structure of the program remains the same.

The first difference is found at the headers: <stdio.h> has been replaced by <iostream>. So now we don’t use printf and scanf but std::cout and std::cin. The std prefix means that cin and cout are found in the standard namespace, them being streams and not functions.

Then, in the first line of the main function we replace uint size = 0; with uint size {0};. In C++ the assignment = can be replaced with curly braces, this feature is optional, we can still do it as we did in C. I did it just to illustrate an interesting difference.

As said earlier, we replaced scanf was replaced by using cin. To use it we use the >> operator (“get from”), as we have the << operator (“put to”) to use cout.

In the for loop we make an interesting change, we iterate over our array, a very useful feature. But we did more than that:

/* simplest case while iterating on the array */
for (int x : arr) { ... }

/* we use "auto", wich guesses the type of the element based on the type or our array */
for (auto x : arr) { ... }

/* another useful C++ feature, we get the element of the array by reference, so we can directly modify x */
for (auto& x : arr) { ... }

Finally we modify x with cin, thanks to our auto& x.