r/C_Programming • • May 21 '26

Question Are runtime created functions possible? (Cursed ideas)

This sounds like a bad idea, but I'm curious if it's even possible. But imagine you have a function that needs different parts of it turned on and off depending on user selected parameters. Instead of a bunch of if statements for each part, can you create the resultant function needed at runtime, and just call that, skipping the need for if statements at every call?

I feel like you could do a list of function pointers, and call them all in sequence, and that also sounds cursed, and not a thing I've even heard of.

But wondering if a solution like: copying the machine code for a function into memory, and then casting the pointer as a pointer to function and calling it, is that even possible.

73 Upvotes

53 comments sorted by

View all comments

Show parent comment

10

u/madvlad666 May 22 '26

A guy at work wrote a thing to do animations on a dot matrix display driven by an 8051. Scrolling and spinning and dissolving, blend colours, etc.

It would prepare the animation by procedurally generating a binary blob of machine code instructions in ram to manipulate the display, then jump to that block of freshly generated code.

So basically optimizing by inlining, except when the animation was done it would use the same ram space to start building new code for the next animation in the sequence.

Cursed is a pretty good word for it tbh