Strange syntax error reported in a range-based for loop
Asked Answered
P

1

7

In Visual Studio 2013, I wrote the following in an empty, brand-new command-line solution:

int main(int argc, char* argv[])
{
    int xs[1];
    for (auto x : xs)
        do
            ;
        while (0);
    return 0;
}

When I compile, I get the following error:

error C2059: syntax error : '}'

on the line containing the single semicolon. Have I found a compiler bug? Or is the range-based for loop subtle beyond my comprehension?

Projection answered 6/3, 2014 at 1:1 Comment(9)
Compiles with Clang, so I'd say bug.Parabolic
isn't your code read as for (auto x : xs) { do; } while(0); ?Sines
Compiles with g++ 4.8.Ozellaozen
@Sines I'm pretty sure it's parsed as for (auto x : xs) { do; while(0);}, otherwise it should be an error since do by itself is not a valid keyword. He's got an empty statement within the do ... while.Adachi
billz - I expect so, since your code gives an identical error in my compiler. But if so, it must be a bug, since a do-loop has to have a while in it, and the whole lot should be parsed as a single statement..Projection
@Projection Seems the only way to get VS2013 to compile this is to add braces around the entire do ... while statement; or replace the range-for with a regular old for statement. You should file a bug report on connect.microsoft.comAdachi
@Adachi Good idea, but if they want me to agree to eight screenfuls of dense legalese to submit a bug report, they can go jump. Or better, read stackoverflow like the rest of us.Projection
To be fair someone did write it over a weekend.Innocuous
Neither clang, nor gcc has any problems with it. It seems like a bug in VS2013.Meprobamate
P
5

To summarise the comments for anyone coming this way in the future:

This is clearly a compiler bug in Visual Studio 2012 and 2013. The error message given by Visual Studio is clearly bogus, and other compilers work as expected.

The simplest workaround for me is to just put braces around the whole do-while loop like so:

int main(int argc, char* argv[])
{
    int xs[1];
    for (auto x : xs)
    {
        do
            ;
        while (0);
    }
return 0;
}

Thanks to everyone for your help.

Projection answered 6/3, 2014 at 20:54 Comment(3)
FTR, this is fixed in Visual Studio 2015 blogs.msdn.com/b/vcblog/archive/2015/07/01/…Occult
But I'm still having this issue in visual studio 2015 (I just updated to Update 2 and it is still present)Pronominal
@kovarex, I cannot confirm this bug in VS2015 Community Update 2. It compiles the initial code sample without problems. But it seems that VS2015 automatic code formatter have problems with indentation. Minor trouble I'd say.Magnusson

© 2022 - 2024 — McMap. All rights reserved.