Tag: C++

What’s wrong with you, std::optional?

“He Who Laughs Last Is At 300 Baud”, is possibly a long-forgotten joke, but sometimes C++ standard is like using a 300 baud modem, discovering “innovations” tens of years after other less committee-centric languages discover and apply them.

Let’s take the std::optional which tries to mimic the Option monad available in other languages. Since 1990 there has been a resurgence of functional programming languages in the mainstream – Haskell (1990), and Scala (2004) just to name two that have Option since their first version.

Continue reading “What’s wrong with you, std::optional?”

As Smart as a Smart Type – Practice (C++)

In theory, practice and theory are the same, in practice they are not. So, after having read how brilliant and smart smart-types are, it is now time to have a closer look at the compiler and figure out what C++ can offer.

After my last post, I found that Smart Types are also known as Refined (or refinement) Types. And here is a notable implementation for Scala.

Simple things first, if you need a type with a bunch of possible values, don’t use int & #defines, don’t use bool either (please), use enum, or, even better enum class.

Now that we’ve done with the trivialities, let’s proceed to something more challenging – numeric types. Ideally, we want some template code that wraps the numeric type and saves us the boredom of writing all the usual +, -, *, /, ==, !=, <… operators, while letting us define the rules of the existence of the represented type.

Continue reading “As Smart as a Smart Type – Practice (C++)”

Watchdogging the Watchdog

Maybe one of the main differences between embedded software/PC programmers and server/backend programmers is their attitude toward system resets. A server programmer will try as hard as possible to avoid any sort of system reboot since this could make a bad situation even worse. They would always strive for graceful service degradation (i.e. the system would not provide its full or top-level service) whenever forced to take action against unexpected or failing conditions.

Continue reading “Watchdogging the Watchdog”

Is C++ Ready for Functional Programming? – Wrap Up

Wrap Up

Recently I had the questionable pleasure of watching “Cosmic Sin” courtesy of Netflix. The movie is a sci-fi show starring Bruce Willis. I was lured into wasting my time on it, by the trailer promising a space-operish feat and I took the presence of such a star playing in the movie for a warranty on quality. I couldn’t be farther from the truth.

The movie plays out confusingly, lacking a coherent script and motivated actors, pushing the watcher into an undefined state (not UB luckily). The helpless watcher, astonished by how bad a film could be, hopes until the very last for something interesting and entertaining to happen until the mixed relief-disbelief emotion of closing titles puts an end to the suffering.

When thinking about C++ and functional programming I have some of the feelings I had watching the movie. Before being persecuted by my friends from the C++ community I have to make clear that C++ is not that bad, although there are some similarities.

Continue reading “Is C++ Ready for Functional Programming? – Wrap Up”

Is C++ Ready for Functional Programming? – Types

Types

Featured image vector created by brgfx – www.freepik.com

Although functional programming can be done in a dynamically typed language (Lisp, the functional programming language forerunner, had no types), strong static type adds a very natural complement to functional programming.

From a mathematical point of view, a function sets a relationship between the set defined by the function argument (domain in math speaking) and the corresponding results (co-domain). Algebra studies exactly these relationships and may help the programmer in proving certain properties of the functions composing the programs.

Algebraic Data Types (ADT) are aggregated types in the algebra context. Two ADTs are of particular interest – sum types and product types. With sum and product referring to the resulting number of possible values (i.e. cardinality of sets).

Continue reading “Is C++ Ready for Functional Programming? – Types”

Is C++ Ready for Functional Programming? – Standard Library

Time to take a closer look to the standard library from the functional programming point of view.

In the first installment of this series, I stated that using a library to implement functional programming structures would not be an ideal solution, but as C language pioneered in the 70s, part of the language finds its proper location in a library.

C++ standard library has grown disorderly oversize during the years, so let’s have a look at what kind of support is available for those that want to use C++ with the functional paradigm.

Continue reading “Is C++ Ready for Functional Programming? – Standard Library”

Is C++ Ready for Functional Programming? – Functions, Functions for Everyone!

In this second installment, I’ll look closer to the core of functional programming – functions. When I started programming, BASIC was the language of choice… the only available choice. And no, it wasn’t the quite convoluted Visual Basic, but the old plain, primitive BASIC with line numbers and poor syntax.

In those days I just used GOTOs and looked with suspicion at the GOSUB/RETURN wondering why in the world I would need to automatically return when I could GOTO everywhere I needed… But I’m digressing. It is just for saying that (besides yours truly could be not the best authority on this matter), programming languages have come a long way and the poor BASIC programmer had to spin the evolution wheel for quite a while to reach to concept of function as presented in this post.

Continue reading “Is C++ Ready for Functional Programming? – Functions, Functions for Everyone!”

Is C++ Ready for Functional Programming? – Intro

Design by committee (DbC) was never meant to be a compliment. In DbC, every decision has to go through a debate and be subjected to a political process. Because of the needed compromise among the parts, the resulting artifact usually tends to be clunky and patchy, lacking elegance, homogeneity, and vision.

C++ is quite an old language, not as old as its parent C, or other veterans of the computer language arena, but the first standard is now 23 years old and the language was quite well-formed and aged to mature its dose of quirks, long before that.

Continue reading “Is C++ Ready for Functional Programming? – Intro”

Comprehensive For in C++

Switching back and forth between Scala and C++ tends to shuffle ideas in my brain. Some ideas from Scala and the functional world are so good that is just a pity that can’t be applied directly and simply in C++.

If you carefully look into idiomatic C code for error handling, it is easy to find a lousy approach even in industrial code. I’ve seen a lot of code where not every return value was examined for an error, or not everything was thoroughly validated, or some code was executed even when it was not needed because an error occurred but was too cumbersome to provide the escape path.

In C++ things are a bit better, thanks to the exception mechanism, but exceptions are such a pain in the neck to get right and to handle properly that error management could soon turn into a nightmare.

Error handling in C and C++ is so boring and problematic that the examples in most textbooks just skip it.

(featured image by Nadine Shaabana)

Continue reading “Comprehensive For in C++”

A Type with Character

So, you know everything about C++ integral types, don’t you?

I thought I did, until when I enabled clang-tidy on my project. It all started with the rather innocent-looking warning:

warning: use of a signed integer operand with a binary bitwise operator

It looked somewhat less innocent when, examining the line, I saw no evidence of signs.

But, let’s start from the comfort zone (at least, my comfort zone):

unsigned x = 32;

The type of ~x (bitwise negation) is still unsigned. No surprise here, really obvious. The diligent programmer finds that the data fits in a smaller integer and writes:

   uint8_t s = 42;

Can you guess the type of ~s? Give it a try, really. Ready? Well, the type of ~s is… int. What? A quick check of other expressions involving uint8_t yields the same … fascinating result. Apparently these expressions are all converted into int.

In other words (and with a bit of syntax bending) uint8_t+uint8_t -> int, uint8_t<<uint8_t -> int, uint8_t+1 -> int. Let me rephrase that, in every expression an uint8_t type is converted to int.

Time for some Internet Duckduckgoing :-).

Back to our uint8_t (that is nothing but an unsigned char in disguise). When a char value, be it signed, unsigned or plain is encountered in an expression (in C++ standard jargon, a prvalue) it is promoted to int pretty much on every common CPU. On exotic architectures, char and int could have the same size, so int could not hold every possible value of char and therefore it is turned into an unsigned. From a strictly rigorous point of view, the signedness of the type of uint8_t in expression is machine-dependent. Keep this in mind if you aim to write really portable code 😉 (*)

You can find a very good (and somewhat frightening) explanation here.

But I’d like to add something beyond the standard technicalities and look at the reasons for why this is like this and what we can take home.

First, it is important to fix that in C (and C++ by extension) the int/unsigned type is mapped to the most efficient word of the target processor. The language provides that, as long as you use int/unsigned (without mixing them) in an expression, you get the most performing code.

Also, the language mandates that an int be at least 16 bits wide and at most the same size of a long.

What if you need to do math on 8bits data on a 32bits architecture? Well, you need assembly code to insert mask operation for cutting away the excess data in order to reach the right result.

So, the C language opts for the best performance turning everything into int, avoiding the extra assembly for masking and let the programmer arrange the expressions with cast here and there if anything different is desired.

Unexpected type promotion, sign change, and performance penalty should be three good reasons to avoid using anything different from int and unsigned in expressions (or long long when needed) and keep intXX_t and uintXX_t for storage.

Note that this applies also to function arguments. It happens quite frequently to read APIs where types for integer arguments are defined as the smallest integer capable of holding the largest value for a given parameter. That may seem a good idea at first since the API embeds in the interface the suggestion to the user for a proper range.

In fact, this has to be balanced against the aforementioned problems and don’t really enforce the constraints for two reasons – first, you can actually pass any integral type and get not even a warning and second, possibly your accepted range is a subset of all the possible value of the type, therefore the user is still required to read the documentation.

Finally, when in doubt, use the compiler 🙂 Finding types of expressions via the compiler could be not the most intuitive task. Below you find the code I used for my tests. Happy type-checking!

/* Linux only, sorry */
#include <iostream>
#include <cstdint>
#include <cxxabi.h>

int main()
{
    uint8_t a = 42;
    std::cout << abi::__cxa_demangle(typeid( a ).name(), nullptr, nullptr, nullptr) << "
";
    std::cout << abi::__cxa_demangle(typeid( ~a ).name(), nullptr, nullptr, nullptr) << "
";
    std::cout << abi::__cxa_demangle(typeid( 42u ).name(), nullptr, nullptr, nullptr) << "
";
    std::cout << abi::__cxa_demangle(typeid( ~42u ).name(), nullptr, nullptr, nullptr) << "
";
    return 0;
}

(*) Also keep in mind, if you strive to write a portable code, that uintXX_t types may not exist for exotic architectures. In fact, the standard mandates that if the target CPU has no 8 bits type then uint8_t be not defined for such target. You should use uint_least8_t (meaning a data type that has at least 8 bits) and uint_fast8_t (a data type that is the most efficient for operations with 8 bits).