Thoughts on extending C
From time to time I have thought about ways I might improve C. Here are some of the more coherent ones that I have taken time to write out. The goal is to extend the language in a way that existing code continues to compile as-is, so each extention idea is expressed using some form of currently-invalid syntax.continue case
In typical use of switch statements, fallthrough between cases is not intended
and yet an implicit fallthrough takes less code than breaking as intended.
Why not add an explicit fallthrough keyword or statement, and then warn or even
error on implicit fallthrough? It could be accomplished using magic comments,
but I think it would be cleaner to write as next case;
or re-using
keywords even more, continue case;
though it's slightly uglier.
Putting a re-used keyword first ought to make it far easier to parse, so I
currently favour the latter slightly.
Taking it one step further, continue case some_constant;
could
be used as a goto, but with the added clarity that it can only target the
current switch block. It would allow for some code flows that are currently
hard to represent without duplication (cases A and B both continue to C).
It would also function as a slightly tidier way to implement a state machine
than a switch within a loop, and slightly easier to reason about than using
pure goto for that purpose.
The logical conclusion is continue case an_expression;
, which
is more concise than storing the initial switch value in a variable and
setting up a loop or label to return to a point between that assignment
and the switch statement itself.
tuple returns
Todo: write this stuff.
For now, summary:
[int, char*] a_function() { return [4, "foo"]; }
called like [x, str] = a_function();
It would work similar to returning a struct then assigning variables from
it, except that the optimizer can more explicitly specialize for omitted
values. It can destructure into both existing variables and newly-declared
variables ([x, char *str] = a_function();
).
structured varargs
Todo: write this stuff.
Continuing from above, what if you could write
void a_function(int a, [int, char*] arg){}
and it would be like a vararg function but the compiler checks that
parameters come in appropriately-typed groups. Consider a function that
constructs something like the Map<String, int>
found
in a number of other languages.