By "runtime metaprogramming" I mean changing the actual code at runtime.
For example, take this code:
while (true) {
if (flag) {
//do stuff
}
//do other stuff
}
Let's say something happens so that flag will always be false/true, so there is no need to keep checking its value. It would be nice to just "get rid" of the if statement. Obviously there might just be better design in the code before execution to handle this, but this is just an example.
CodePudding user response:
C does not have facilities for modifying code at runtime like that. This is because C code is compiled to machine code, and modifying machine code is very difficult, insecure, and non-portable. If you're interested, see the Wikipedia article on Self-modifying code.
In theory, if you really needed to, you could hoist the test for flag
further back, by writing three sets of functions (one where flag
is known to be always true, one where it's always false, and one where it could be either) and switch between those sets of functions at an earlier time. However, the code complexity and performance impact of maintaining three separate copies of the functions will not be worth the microscopic speedup from removing one easily-predicted branch.
If you're concerned about the performance of your application, you will find better opportunities for optimization elsewhere.
CodePudding user response:
Does C have any runtime metaprogramming functionality?
The abstract machine that a compiler has to have in mind when optimizing and organizing instructions does not involve the volatile nature of someone flipping a bit somewhere in memory that it can't control. That "somewhere" may not even exist after the compiler has done its job.
In the case of the true
check in your loop:
None of the compilers I know will actually produce code that checks if there is a true
there. It's just a an infinite loop.
Why? The compiler has to produce a program acting "as-if" it did all you instructed it to do. If you instruct it to check if true
is true
, the "as-if" rule tells the compiler that it can with a 100% certainty rely on the fact that you want this loop to go on forever. No runtime check necessary.