int* oracle();
int foo() {
int x = 1;
*oracle() = 42;
return x;
}
Is the above program allowed to return anything other than 1 in your language? int* oracle();
int foo() {
int x = 1;
*oracle() = 42;
return x;
}
Is the above program allowed to return anything other than 1 in your language?For some high-quality further discussion, see Ralf Jung's series of blog posts starting with https://www.ralfj.de/blog/2018/07/24/pointers-and-bytes.html
However, given how low-level a language C++ is, we can actually break this assumption by setting i to y-x. Since &x[i] is the same as x+i, this means we are actually writing 23 to &y[0].
But that is undefined, you can't do x + (y - x) ie a pointer arithmetic that ends outside of bounds of an array. Since it is undefined, shouldn't C++ assume that changing x[..] can't change y[0]edit: welp, if I read a few more lines into article I would see that it also tells it is undefined
Note that rand() returns 32-bit value so you have to call it twice and merge the results to obtain a 64-bit pointer.
If forging pointers had defined behaviour, it would be impossible to use the language sanely or perform any kind of optimization.
Sure different compilers might allow inlining assembly or some other ways to access x on previous stack perhaps but then it is not really "C"
The majority of useful optimizations can be kept in a "Sane C" with either code style changes (cache stuff in local vars to avoid aliasing for example) or with minor tweaks to the standard.
“Don’t optimize this, read and write it even if you think it’s not necessary” is a very rare case so it shouldn’t be the default. If you want it, use the volatile keyword.
There’s no need to reword the standard to assume the register behavior if the variable’s address hasn’t been taken. That’s already how it works. In this example, if you escape the value of `&x`, it’s not legal to optimize this function to always return 1.
For example: If the oracle function returns an invalid pointer, then dereferencing that pointer is UB, and therefore the program isn't a valid C program.