|
|
|
|
|
by pascal_cuoq
2250 days ago
|
|
One concrete reason why “unspecified” means “anything and not always the same thing” is to enable the maximum of optimizations. Write a function c that compares pointers in a compilation unit, and in another compilation using, define: int a, b;
X1 = (&a == &b + 1);
X2 = c(&a, &b + 1);
The compiler can optimize the computation of X1 on the basis that comparing an offset of &a to an offset of &b will always: - be false
- or invoke undefined behavior
- or be unspecified
But the optimization will not apply to the computation of X2, so the two variables X1 and X2 can receive different values when you execute this example, although they appear to compute the same thing. |
|
Imagine a standard stated that > and < character comparisons involving '%' were unspecified. Why would this be good? It wouldn’t, so it’s not in any standard. But specifically it wouldn’t because (a) nobody writes ch < '%', and (b) if they did, compilers couldn’t make programs any faster, more portable, etc, because of its inclusion.
I guessed above that this is kinda like having hashmaps iterate in a random order: compilers do spooky things when you try to check whether two allocas/mallocs are adjacent, so don’t do it. Is that accurate? Or does it mean that compilers can move things around on the stack if they want, without worrying about updating the registers or locations that store the pointers, i.e. this is mainly to make compilers easier to write? If it’s that, I imagine I would want some other pointer comparisons on the list. The reason it’s in there is what I wanted you to shed some light on.