3

In Visual Studio 2013, the following code snippet generates the compile error

error C2440: 'initializing' : cannot convert from 'TestSubStruct' to 'int'

#include <stdio.h>

typedef struct TestSubStruct {
    int test;
} TestSubStruct;

typedef struct TestStruct {
    TestSubStruct sub;
} TestStruct;

int main(int argc, char* argv[])
{
    TestSubStruct r = {0};
    TestStruct vp = { .sub = r}; // this line causes the error
    return 0;
}

This can easily be rewritten so that it compiles, but what I want to know is why the code doesn't compile as is. Does it violate the specification for static initializers somehow? Is this just an issue with MSVC or do other compilers fail to build this as well?

EDIT: It seems from the commenters that this is an MSVC issue. In that case, my question is: what are the exact limitations of MSVC 2013's support for static initializers?

John
  • 151
  • 4
  • 2
    Compiles ok in gcc and clang. – Charlie Burns May 17 '14 at 04:03
  • Causes undefined behaviour since `r` is not initialized – M.M May 17 '14 at 04:56
  • I've amended the question so that `r` is initialized and the error is still the same. – John May 17 '14 at 05:52
  • @johnpeeb, it must be an MS thing. I confirm that it builds without error on gcc 4.3 – Mahonri Moriancumer May 17 '14 at 06:55
  • @CharlieBurns and MahonriMoriancumer: Thanks for taking the time to try compiling in other compilers. That just leaves the question of what MSVC's limitations are with supporting static initializers. (It does have at least some support for them.) – John May 17 '14 at 07:18
  • @johnpeeb, I changed from `{ .sub = r};` to `{ .sub = (TestSubStruct)r}`, and still got an error from VS2013: `error C2440: 'type cast' : cannot convert from 'TestSubStruct' to 'TestSubStruct'` Classic Microsoft. – Mahonri Moriancumer May 17 '14 at 07:25
  • 1
    It is a C99 feature, MSVC implements C89. Just { r } is the obvious workaround here. – Hans Passant May 17 '14 at 10:35
  • 2
    @HansPassant According to the VS docs, VS 2013 is supposed to have support for designated initializers even though they are a C99 feature. Also, I just found [this recent confirmed bug report](http://www.beta.microsoft.com/VisualStudio/feedback/details/805981/msvc-2013-c99-designated-initializers-cannot-initialize-unions-within-structs) which looks similar to the issue I'm experiencing. So perhaps it is just a bug. – John May 17 '14 at 21:35

0 Answers0