1

How is it possible that the following code is successfully compiled by GCC version [6..10] ?

int main(int argc, char *argv[])
{
    auto const answer = 42;
    auto lambda = [&answer] {};
    auto *p = &(lambda.__answer);

    return p != &answer; // return 0 (success) if they are the same
}

Is GCC leaking its internal representation of lambdas into the user's program?

godbolt

Bulletmagnet
  • 5,665
  • 2
  • 26
  • 56

1 Answers1

4

[lex.name]
(3) In addition, some identifiers are reserved for use by C++ implementations and shall not be used otherwise; no diagnostic is required.
(3.1) Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.

[intro]
If a program contains a violation of a rule for which no diagnostic is required, this document places no requirement on implementations with respect to that program.

[defns.undefined]
undefined behavior: behavior for which this document imposes no requirements.

Thus the program behaviour is undefined.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • +1 I think that's pretty much it. You might want to explain that the original code triggers UB, maybe the OP didn't understand it. – Lorah Attkins Aug 02 '20 at 23:04
  • Are you saying that the standard allows GCC to accept this code? – Bulletmagnet Aug 03 '20 at 08:52
  • 1
    @Bulletmagnet The standard says "no diagnostic is required" and I can add nothing to it. – n. m. could be an AI Aug 03 '20 at 09:05
  • Invoking [lex.name](3) here doesn't sound right; that would make any program that uses e.g. `__builtin_alloca()` ill-fromed (NDR). – Bulletmagnet Aug 06 '20 at 06:54
  • 1
    @Bulletmagnet A program that uses e.g. `__builtin_alloca()` has UB as far as the standard is concerned. Implementations are allowed to have documented extensions though. If `__builtin_alloca()` is documented by some implementation, it is OK to use it with that implementation. The standard does not make guarantees w.r.t. such a program, the implementation does. – n. m. could be an AI Aug 06 '20 at 07:08