<p>On today's computers, in today's environment, it won't work. Program memory is out of bounds for writing, data memory is out of bounds for execution, both for very good reasons: They have been vehicles for grievous security failures.</p>
<p>It is hard enough to write a program, harder still to write a program that in turn writes a program. Getting it to reliably change itself is insane.</p>
<p>Teaching people to do this serves no purpose I can see.</p>

CC BY-SA 4.0
2021-05-04T05:04:53.050Z
I'm not asking about allowing a program to self-modify itself in a completely arbitrary way; I'm asking about using it as a technique for solving a specific problem for which there isn't enough information at the time the program is written. It's possible to establish -- and guard against -- invalid operations, just like it's possible to establish similar limits for other program operations.
Zev Spitz
CC BY-SA 4.0
2021-05-03T20:53:13.890Z
2021-05-03T20:53:13.890Z
vonbrand
<p>I haven't tried to build this but it seems to have the right characteristics</p>
<p><a href="https://animalgame.com" rel="nofollow noreferrer">The Animal Game</a></p>
<p>In theory, new animals could be captured with new classes, extending the known list.</p>
<p>The user thinks of an animal and the program asked a series of yes-no questions to &quot;guess&quot; the animal: &quot;Does it have antlers?&quot; etc. Depending on the answer, it asks a different question. The structure of the run-time is a tree with concrete values at the leaves: &quot;Is it a moose?&quot;.</p>
<p>If the machine &quot;guesses&quot; wrong, the user then supplies a question that would distinguish the guess from the animal chosen: &quot;What question would distinguish an <em>antelope</em> from a moose?&quot;. Then the game restarts, remembering the new animal and where it fits in the hierarchy.</p>

CC BY-SA 4.0
2021-03-15T15:46:00.357Z
I still don't know what a _di-monarchial caste colony_ is (from one of the questions). :) But this looks excellent, particularly as it neatly parallels the dynamic type handling I described in the question.
Zev Spitz
CC BY-SA 4.0
2021-03-15T15:56:17.800Z
Since users supply the new "animals", some of them will just toy with the system.
Buffy
CC BY-SA 4.0
2021-03-21T04:41:49.897Z
This was an early 1980's game on an Apple-II. But I think it just used a text file to store the Q's (but Apple-II's allowed self-modifying code, mostly as copy-protection).
Owen Reynolds
CC BY-SA 4.0
2021-03-21T11:23:25.647Z
@OwenReynolds, it has a lot of possible implementations, including one using SQL in a database course. Another might use a spreadsheet.
Buffy
CC BY-SA 4.0
2021-03-15T15:38:48.580Z
2021-03-15T15:38:48.580Z
Buffy
<p>I didn't write any myself, but I encountered several self-modifying MS-DOS batch files (this is possible due to the OS closing the batch file before executing each line), especially during the <span class="math-container">$1980$</span>'s. I'm not sure if batch files fit within your definition of &quot;programs&quot;, or if this usage was from too long ago since the needs &amp; reasons for this (i.e., primarily due to only a minimal amount of memory being available) don't generally apply now to modern computers. Nonetheless, having batch files modify themselves is a relatively simple concept, and was similarly done for fairly basic reasons as well, so this might make good examples for teaching purposes.</p>
<p>I recall self-modifying batch files were used in several situations, but the main one was to change options based on user feedback. Wikipedia's <a href="https://en.wikipedia.org/wiki/Self-modifying_code#Compound_modification" rel="nofollow noreferrer">Self-modifying code</a> gives an example where a batch file runs a program that changes the file itself to next run what the user requested. However, I also recall seeing &amp; using a batch file with a fairly complicated (at least for a batch file) menu type system, with the commands directly modifying the file itself based on user feedback, return codes from the menu and/or other programs which were run. I no longer have a copy of this batch, or any other related, files. As this was over <span class="math-container">$30$</span> years ago, I don't recall any other details. Also, I haven't been able to find any such similar example online. Nonetheless, in <a href="https://stackoverflow.com/q/906586/11726740">Changing a batch file when its running</a>, several answers, such as the <a href="https://stackoverflow.com/a/9651656/11726740">answer</a> by <a href="https://stackoverflow.com/users/1012053/dbenham">dbenham</a> and the <a href="https://stackoverflow.com/a/9635783/11726740">answer</a> by <a href="https://stackoverflow.com/users/463115/jeb">jeb</a>, give other examples of direct self-modifying batch files.</p>
<p>Note that, as the Wikipedia article section states, these batch file self-modifications were done primarily due to how limited memory generally was in personal computers back then. Most, if not all, of the other reasons people wrote &amp; used self-modifying batch files back then, as I recall, were also due to these significant memory limitations.</p>

CC BY-SA 4.0
2021-03-15T02:04:41.817Z
2021-03-15T21:43:57.813Z
2021-03-15T21:43:57.813Z
John Omielan
<p>.NET expression trees can be used to write self-modifying compiled programs -- because it is possible to construct and compile a method at runtime, it is also possible for a method to rewrite its own code at runtime.</p>
<p>.NET leverages this for dynamic typing in C#, taking advantage of the fact that even for dynamically-typed code, the vast majority of usages at a given call site will have the same types. Each dynamic call site has a corresponding expression tree, and a corresponding method. Every time a new set of types is encountered at this call site, additional logic which handles the new types will be added to the expression tree, which is then compiled into a new method; this new method becomes the method corresponding to this call site.</p>
<p>Aside from the fact that I haven't been able to see this mechanism running live, I feel it's too complex and distracting from the simplicity of the primary concept.</p>
<p>What relatively simple use case could I use to demonstrate the value of this property, of allowing the writing of a self-modifying program? Is there a standard example?</p>

CC BY-SA 4.0
2021-05-08T18:31:02.100Z
If you have to struggle to come up with a relatable, practical usage example, why teach the concept at all?
ggorlen
CC BY-SA 4.0
2021-05-09T05:07:33.193Z
@ggorlen My goal here is to teach .NET expression trees, which are types and objects that model pieces of programs. Expression trees have two use cases: 1. translating various programming operations for use in another environment, and 2. enabling dynamic programming languages in a statically typed world. Self-modifying code is part and parcel of 2.
Zev Spitz
<teaching-analogy><computational-thinking>
Simple use case for self-modifying programs
# Simple use case for self-modifying programs

(Asked by: username_0 on 2021-03-14)

.NET expression trees can be used to write self-modifying compiled programs -- because it is possible to construct and compile a method at runtime, it is also possible for a method to rewrite its own code at runtime.

.NET leverages this for dynamic typing in C#, taking advantage of the fact that even for dynamically-typed code, the vast majority of usages at a given call site will have the same types. Each dynamic call site has a corresponding expression tree, and a corresponding method. Every time a new set of types is encountered at this call site, additional logic which handles the new types will be added to the expression tree, which is then compiled into a new method; this new method becomes the method corresponding to this call site.

Aside from the fact that I haven't been able to see this mechanism running live, I feel it's too complex and distracting from the simplicity of the primary concept.

What relatively simple use case could I use to demonstrate the value of this property, of allowing the writing of a self-modifying program? Is there a standard example?

**Tags:** teaching-analogy, computational-thinking

> **Comments:**
> **username_1**: If you have to struggle to come up with a relatable, practical usage example, why teach the concept at all?  
> **username_0**: @username_1 My goal here is to teach .NET expression trees, which are types and objects that model pieces of programs. Expression trees have two use cases: 1. translating various programming operations for use in another environment, and 2. enabling dynamic programming languages in a statically typed world. Self-modifying code is part and parcel of 2.  

---

## 3 answers

### Answer by username_3 on 2021-03-15. Score: 3 | Accepted answer

I haven't tried to build this but it seems to have the right characteristics

[The Animal Game](https://animalgame.com)

In theory, new animals could be captured with new classes, extending the known list.

The user thinks of an animal and the program asked a series of yes-no questions to "guess" the animal: "Does it have antlers?" etc. Depending on the answer, it asks a different question. The structure of the run-time is a tree with concrete values at the leaves: "Is it a moose?".

If the machine "guesses" wrong, the user then supplies a question that would distinguish the guess from the animal chosen: "What question would distinguish an *antelope* from a moose?". Then the game restarts, remembering the new animal and where it fits in the hierarchy.

> **Comments:**
> **username_0**: I still don't know what a _di-monarchial caste colony_ is (from one of the questions). :) But this looks excellent, particularly as it neatly parallels the dynamic type handling I described in the question.  
> **username_3**: Since users supply the new "animals", some of them will just toy with the system.  
> **username_4**: This was an early 1980's game on an Apple-II. But I think it just used a text file to store the Q's (but Apple-II's allowed self-modifying code, mostly as copy-protection).  
> **username_3**: @OwenReynolds, it has a lot of possible implementations, including one using SQL in a database course. Another might use a spreadsheet.  

---

### Answer by username_5 on 2021-03-15. Score: 5

I didn't write any myself, but I encountered several self-modifying MS-DOS batch files (this is possible due to the OS closing the batch file before executing each line), especially during the $1980$'s. I'm not sure if batch files fit within your definition of "programs", or if this usage was from too long ago since the needs & reasons for this (i.e., primarily due to only a minimal amount of memory being available) don't generally apply now to modern computers. Nonetheless, having batch files modify themselves is a relatively simple concept, and was similarly done for fairly basic reasons as well, so this might make good examples for teaching purposes.

I recall self-modifying batch files were used in several situations, but the main one was to change options based on user feedback. Wikipedia's [Self-modifying code](https://en.wikipedia.org/wiki/Self-modifying_code#Compound_modification) gives an example where a batch file runs a program that changes the file itself to next run what the user requested. However, I also recall seeing & using a batch file with a fairly complicated (at least for a batch file) menu type system, with the commands directly modifying the file itself based on user feedback, return codes from the menu and/or other programs which were run. I no longer have a copy of this batch, or any other related, files. As this was over $30$ years ago, I don't recall any other details. Also, I haven't been able to find any such similar example online. Nonetheless, in [Changing a batch file when its running](https://stackoverflow.com/q/906586/11726740), several answers, such as the [answer](https://stackoverflow.com/a/9651656/11726740) by [dbenham](https://stackoverflow.com/users/1012053/dbenham) and the [answer](https://stackoverflow.com/a/9635783/11726740) by [jeb](https://stackoverflow.com/users/463115/jeb), give other examples of direct self-modifying batch files.

Note that, as the Wikipedia article section states, these batch file self-modifications were done primarily due to how limited memory generally was in personal computers back then. Most, if not all, of the other reasons people wrote & used self-modifying batch files back then, as I recall, were also due to these significant memory limitations.


---

### Answer by username_2 on 2021-05-03. Score: 0

On today's computers, in today's environment, it won't work. Program memory is out of bounds for writing, data memory is out of bounds for execution, both for very good reasons: They have been vehicles for grievous security failures.

It is hard enough to write a program, harder still to write a program that in turn writes a program. Getting it to reliably change itself is insane.

Teaching people to do this serves no purpose I can see.

> **Comments:**
> **username_0**: I'm not asking about allowing a program to self-modify itself in a completely arbitrary way; I'm asking about using it as a technique for solving a specific problem for which there isn't enough information at the time the program is written. It's possible to establish -- and guard against -- invalid operations, just like it's possible to establish similar limits for other program operations.  

---

