5

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.

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • 2
    Which version of MSVC? What flags and options do you set or use when building? – Some programmer dude Feb 06 '20 at 12:59
  • That online VC compiler seems to be a developmental version (19.00.23506) judging by the "00" as the second field. Your code compiles without warning or error in Version 19.24.28316 for x64 - however 'strict' I make the settings. – Adrian Mole Feb 06 '20 at 13:24
  • @AdrianMole, I have updated the compiler version in the question. Is there a way to fix it with the older version? Or is 19.24 is too improved compared to 19.14? – iammilind Feb 07 '20 at 03:35
  • You could work around by changing `for (A;B;C){D}` to `{ A; for(;B;C){D} }` – M.M Feb 07 '20 at 03:56
  • @M.M, I already did that. This `for` loop is a part of macro and hence it will change meanings at certain place e.g. `if(xyz) for(...) {} statement;` will have different meanings. Regardless of that, the original problem still persists. – iammilind Feb 07 '20 at 04:39

1 Answers1

1

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

Fedor
  • 17,146
  • 13
  • 40
  • 131