Is taking the address of an undefined function allowed?
Asked Answered
C

1

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.

Carpology answered 1/4, 2020 at 18:46 Comment(5)
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.Eurydice
You are just seeing some sort of optimization. When trying to use x in some way, it doesn't compile: godbolt.org/z/DaisToPalm
@500-InternalServerError should've checked that. The linker throws an error if I disable optimization.Carpology
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.Blackandwhite
@Blackandwhite - 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 requiredCovariance
A
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.

Animate answered 1/4, 2020 at 18:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.