Search code examples
c++visual-c++compiler-errorsc++14anonymous-struct

How to fix compilation errors in MSVC related to declaration of anonymous struct inside a 'for' loop?


We can declare anonymous struct inside for loop as below (g++):

for(struct { bool OK = true; } s; s.OK; s.OK = false)
  std::cout << "Hello, world!\n";

But, this code results in compilation error in MSVC as:

source_file.cpp(7): error C2332: 'struct': missing tag name
source_file.cpp(7): error C2062: type 'bool' unexpected
source_file.cpp(7): error C4430: missing type specifier - int assumed.
Note: C++ does not support default-int

How to fix it?


Version:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.14.26430 for x86
Copyright (C) Microsoft Corporation. All rights reserved.


Solution

  • Please not that MSVC 19.14 shows the error C2062: type 'bool' unexpected even for a named struct S as in this example:

      for(struct S { bool OK = true; } s; s.OK; s.OK = false)
        std::cout << "Hello, world!\n";
    

    Demo: https://godbolt.org/z/Ev1GMGMYd

    I think the easiest fix would be to upgrade to the next compiler version MSVC 19.15 where both issues are fixed. Demo: https://godbolt.org/z/W14dvW5eW