Is self-modifying code possible in a portable manner in C?
The reason I ask is that, in a way, OOP relies on self-modifying code (because the code that executes at run-time is actually generated as data, e.g. in a v-table), and yet, it seems that, if this is taken too far, it would prevent most optimizations in a compiler.
For example:
void add(char *restrict p, char *restrict pAddend, int len)
{
for (int i = 0; i < len; i++)
p[i] += *pAddend;
}
An optimizing compiler could hoist the *pAddend
out of the loop, because it wouldn't interfere with p
. However, this is no longer a valid optimization in self-modifying code.
In this way, it seems that C doesn't allow for self-modifying code, but at the same time, wouldn't that imply that you can't do some things like OOP in C? Does C really support self-modifying code?
Self-modifying code is not possible in C for many reasons, the most important of which are:
Aside from that, self-modifying code is just a really really bad idea. 20 years ago it might have had some uses, but nowadays it will result in nothing but bugs, atrocious performance, and portability failures. Note that on some ISAs, whether the instruction cache even sees changes that were made to cached code might be unspecified/unpredictable!
Finally, vtables have nothing to do with self-modifying code. It's purely a matter of modifying function pointers, which are data, not code.