nielsen
nielsen

Reputation: 7594

Why does temporary struct member not have the expected value in C++?

Consider this code:

#include<iostream>

struct A
{
    int b;
};

int main()
{
    int c = (A() = A{2}).b;  // Why is c zero after this?
    std::cout << "c = " << c << std::endl;
    std::cout << "A.b = " << (A() = A{2}).b << std::endl;
}

In my mind this is two equivalent ways to print the same value, but I get this result (on GCC 7.3.0 under MinGW):

c = 0
A.b = 2

I would have expected c to be 2. Can anyone explain why it is 0?

Upvotes: 9

Views: 137

Answers (1)

rainbow.gekota
rainbow.gekota

Reputation: 1125

As mentioned by @StoryTeller-UnslanderMonica, this is a GCC bug. I tested several versions on godbolt.com. Here's what I found:

  • works as expected on gcc 6.* with c++ 11 and 14
  • fails on gcc 7.*, 8.*, 9.1-4 with c++14
  • works on gcc 7.*, 8.*, 9.* with c++11
  • works on gcc 9.5 with c++14
  • works on gcc 10 with c++ 11 and 14

I compiled with -O3, and tested some with -O0, and optimization level didn't make a difference where I tested.

I'm not sure where to find the bug ticket. Here's a link to the change summary for GCC 9 versions, and Here's a link to the bugzilla tickets resolved by 9.5. I didn't see anything that looked like an exact match. Either I missed it, or the ticket didn't get put in that list (which the change summary page mentions is a possibility).

This list might not be complete (that is, it is possible that some PRs that have been fixed are not listed here).

Upvotes: 1

Related Questions