6

The following code defines the entire program. Is this program standard conformant (with the latest version)?

void foo();

int main()
{
    auto x = &foo;
    return 0;
}

Here is a convenience shortcut.

This code has no practical use, I'm just curious.

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Timo
  • 9,269
  • 2
  • 28
  • 58
  • 1
    This should cause a linker error (unless the useless statement is eliminated completely by the compiler) as you are asking for the address of something that is not fully defined. – 500 - Internal Server Error Apr 01 '20 at 18:50
  • 1
    You are just seeing some sort of optimization. When trying to use `x` in some way, it doesn't compile: https://godbolt.org/z/DaisTo – LoPiTaL Apr 01 '20 at 18:50
  • @500-InternalServerError should've checked that. The linker throws an error if I disable optimization. – Timo Apr 01 '20 at 18:51
  • 2
    An undefined reference normally makes a program ill-formed NDR. Since I doubt a compiler is required to check if `x` is used or not, it should apply here too. – HolyBlackCat Apr 01 '20 at 18:52
  • @HolyBlackCat - There is nothing preventing the compiler from checking if `x` is used either. The standard doesn't prevent a compiler from eliminating variables (like `x`), or evaluation of expressions that initialise them (`&foo`), if it can detect there are no side-effects of the initialisation or usage of the variable. The "as if" rule only requires observable behaviour to be the same. Since `foo()` is not defined in the program the behaviour is undefined, no diagnostic required - and one possible manifestation of that is a linker error (missing symbol `foo()`) but that is not required – Peter Apr 01 '20 at 23:10

1 Answers1

10

Every function that is odr-used requires a definition (no diagnostic required). Taking the address of a function is an odr-use, so this program exhibits undefined behaviour. With optimisations, the address-of is optimised out so it doesn't have a linker error, but it's not required to work.

Artyer
  • 31,034
  • 3
  • 47
  • 75