Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
iammilind Avatar asked Nov 06 '22 10:11

iammilind


1 Answers

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

like image 92
Fedor Avatar answered Nov 15 '22 05:11

Fedor