r/ProgrammingLanguages • • 4h ago

Discussion Compiling to C

Ive found a lot of languages on this sub compile to c code instead of assembly or a backend. I'm curious what the advantages / disadvantages are to this. I know c is pretty optimized so is this an easy way to make a performant language or does it just make it simpler. I dont know c but I know assembly and some QBE so what are the pros and cons to directly compiling to assembly ( is it just more flexibility? etc...)

0 Upvotes

21 comments sorted by

View all comments

2

u/Ifeee001 3h ago

One con that I often see mentioned is that it'll be difficult to express certain things in C. But I personally wouldn't say it's difficult. It'll probably be more difficult in assembly.

An example is if expressions. C doesn't have that. But you could just desugar it into an uninitialised temp variable declaration and update the values at the appropriate place inside the if block. Every path inside the if block must assign to the temp variable. The else block will/must contain an initialization too so you don't get garbage memory.

E.g. let x = 23 if true else 24;

Hypothetical C:

int temp_if
if (true){temp_if = 23;}
else {temp_if = 24;}

const int mangled_x = tempif;

Ignore any errors. You could also take it a step further to "keep the scope clean" and take advantage of existing inclining optimization and make every if expression emit a function that'll return the result. That's probably over kill

Pretty much any common feature can be expressed in C if you're choosing it as your backend.

C also has a lot of hidden foot guns and undefined behavior.