type declaration syntax
Many modern programming languages are influenced by C, though they typically do not adopt its type syntax. C's type declaration can be confusing, and it may not be worth imitating. The most significant issue stems from user-defined types, particularly when using typedef. While structs and unions can still be defined without typedef, each usage must begin with its respective keyword.
This deviation from the typical context-free grammar makes parsing statements like "foo (*) (x);" problematic, as it requires knowledge whether "foo" is a type or not.
Some programming languages, such as Java, C#, and D, mirror C's type declaration syntax, although this is not inherently problematic. However, it can become quite confusing since the type name starts to behave as if it were part of an expression, which is not the case in C. Mixing the two styles is ill-advised, as it leads to an inscrutable type syntax.
Several alternative syntaxes for type declarations exist across various languages. For instance, Go adopts a unique approach by treating the type as its own self-contained expression, placing the identifier first and the type second. This method is reminiscent of a real sequel to C and allows the type to be an arbitrary compound expression while keeping the identifier as a single token.
A pointer type expression is prefixed with an asterisk, and an array is expressed with a square bracket prefix. Although this may seem strange to those familiar with C, it eliminates ambiguity regarding whether an expression represents an array of pointers or a pointer to an array.
Another syntax employs a colon for type annotations, as seen in languages like ML, Rust, Zig, Swift, and Hare. These languages focus heavily on algebraic data types and rarely use pointers. Rust, in particular, uses references with a prefix of "&" to denote the type. It's becoming a common trend to use a single colon for type annotations, with languages supporting different type systems.
However, Python stands out as an exception, employing the colon for type annotations despite using it for unrelated constructs in other contexts. This choice likely stems from the desire to maintain consistency with existing syntax, even if it may prove limiting in certain situations.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.