5
votes

I just bumped into this little error with msvc. It looks like a parsing problem to me but I'm not sure.
The following gives me C2143 syntax error: missing ';' before'}'

#include <vector>

struct X { };

X f(const std::vector<int> v)
{
  for (auto i : v)
    if (true)
      return X{};     // <--

  return X{};
}

int main()
{
  const auto x = f(std::vector<int>{});
}

The next 4 variations compile just fine, though.
This

X f(const std::vector<int> v)
{
  for (auto i : v)
    if (true)
      return X();     // <--

  return X{};
}

and this

X f(const std::vector<int> v)
{
  for (auto i : v)
    if (true) {       // <--
      return X{};     // <--
    }                 // <--
  return X{};
}

and this

X f(const std::vector<int> v)
{
  for (auto i : v) {  // <--
    if (true)
      return X{};     // <--
  }                   // <--
  return X{};
}

and this

X f(const std::vector<int> v)
{
  //for (auto i : v)  // <--
    if (true)
      return X{};     // <--

  return X{};
}

(Sorry for the wall of stupid code.)
Am I missing some arcane rule or is this a compiler bug?

Visual Studio 2015 (v140) Express Edition for Desktop
compiled as x64 in both debug and release mode
all compiler options to their defaults (except for warning level bumped to W4)

1
What version of VS are you using?user657267
Did you enable C++11 in your compilation command? Perhaps your compiler is compiling for C++03.Basile Starynkevitch
It doesn't fail in gcc (with -std=c++11 option, of course). So, it must be a compiler bug.Peregring-lk
I've added some specs at the end.Garp
"wall of code": Full marks for a complete minimal reproducible example at the top, but I suggest that you only need to show the various flavours of the for statement in the alternative. That will make it much clearer what the changes are too.Martin Bonner supports Monica

1 Answers

4
votes

It looks like a compiler bug for me. I can reproduce your error on rextester.com, but on webcompiler.cloudapp.net the code compiles fine (Visual C++ compiler version there is 19.10.24807.0 (x86)).

Also both latest gcc and clang compile the code.

The syntax itself is perfectly valid.