I have a quick question on some stuff I've seen in episode 124: https://www.youtube.com/watch?v=W_szrzjYuvs&t=818s .
Here Casey is talking about the compiler making decisions and possibly excluding things. Under what context does this happen? I am slightly confused on what he is referring to here. I was under the impression that the code gets compiled and then ran separately and thus the compiler had no impact on runtime decisions in the program. Is he speaking about the compiler excluding stuff at compile-time in prediction of how things may play out at runtime? Thanks.
When you write code, you tell the computer WHAT to do. The compiler tells the machine HOW to do it.
Modern compilers have tons of optimization technique to make your code run faster. Also, computer has a memory hierarchy. Fastest is the registers, then L1-4 caches, then main memory, and slowest is harddrive. Running programs are stored in the main memory. Thus, when you want to read something, you have to load it from the main memory.
For a variable that rarely gets modified but being read very often, the compiler can optimize reading by generating machine-level instruction to load the variable into a register(or a cache) and read from the register(or cache). In other word, a copy was made for faster access.
This optimization is not OK in a multi-threading environment. In this situation, we're reading from a snapshot; the actual variable may be modified in the main memory by something else. Using volatile prevents this optimization and force the compiler to load the variable from main memory for each read.
You also mention about compiler excluding stuff at compile time. An example of this is the Return value optimization.
int a = 3+3;
When compiling, the Compiler may optimize away the variable 'a' and generates machine code closer to this