c++ type annotations

C's type annotation system can be pretty unintuitive at first, at least compared to what most modern langauges do. this boils down to the following: most languages will directly state the type of the variable. x is an int, x is a string[], x is a Widget. C, however, tells you what operations you need to apply to the variable to get the type specified. c is an int, *c is a char, c() is a short, *(*c[])()[] is an unsigned long. this is perfectly fine, and only strange in hindsight when almost eevery other language does the opposite.

the actual problem arises when we get to C++, a language which takes C and attempts to tack modern functionality onto it. most C code is supposed to run in C++, so C++ has the same basic syntax. the problem is, of course, that this basic syntax has holdovers that do not extend well. one prominent example is C++'s reference types.

C++'s reference types are an alternative to pointers that make them more restricted and better for many scenarios. the problem is that if c is a reference to a short, we can get this short just by accessing c; therefore, in the C typing system, we would annotate it as short c. this will obviously not do, so C++ uses short &c for reference types. the obvious problem is that &c is not a short, breaking the rules of the system. rvalue references (which, after much reading, i still do not understand intuitively) use short &&c, which makes even less sense.

another example is the new type alias syntax, which completely breaks the rules that C established. C used typedef, which follows the same rules as variable type annotations. typedef short *(*t)() means that, given a variable of type t, a short can be accessed with that syntax. (in this case, it's a function pointer that returns a short *.) the way we express this in C++ is using t = short *(*)(), a nonsensical mess of asterisks and parentheses.

these examples show what i see as a fundamental problem with C++: it tries as hard as it can to C rules despite not being able to since the C rules weren't meant for modern paradigms. the result is a large pile of nonsense with deceptive syntax, albeit a very fast one.

moral: there is none i just thought it was neat. this used to say "use rust" but that's silly, C++ is prefectly usable and quite nice for certain applications, and even if the language is kinda bad it still does the things you want. (although rust is pretty cool! you should check it out!)

P.S.: could anyone explain to me how std::move works? or universal references? this is getting real confusing sorry

cc0 everything on this site is freely available under CC0 1.0 Universal.

home blog