Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird compiler error

Tags:

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)

like image 395
Garp Avatar asked Dec 21 '16 06:12

Garp


1 Answers

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.

like image 57
Edgar Rokjān Avatar answered Sep 25 '22 16:09

Edgar Rokjān