Preamble:
I know that there are quite some topics with the same or a similar title. Keep reading and you will understand my case.
New to C++ I'm currently reading a book that quite obviously has a corrupt example excercise.
My code
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
int main(int argc, char const* argv[]) {
Point p1{100, 200};
auto [a, b] = p1;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
auto& [c, d] = p1;
c += 50;
d += 50;
cout << "p1.x = " << p1.x << endl;
cout << "p1.y = " << p1.y << endl;
return 0;
}
is almost an exact copy of the book. I only splitted the original one line cout into two lines and used namespace std instead of std::. Other than that the code is exactly like the example in the book.
Just to be 100% sure I'm not just having a typo, I donwloaded the example file from the books website.
We both get the same errors:
structuredBinding.cpp: In function ‘int main(int, const char**)’:
structuredBinding.cpp:14:7: error: expected unqualified-id before ‘[’ token
auto [a, b] = p1;
^
structuredBinding.cpp:16:20: error: ‘a’ was not declared in this scope
cout << "a = " << a << endl;
^
structuredBinding.cpp:17:20: error: ‘b’ was not declared in this scope
cout << "b = " << b << endl;
^
structuredBinding.cpp:19:8: error: expected unqualified-id before ‘[’ token
auto& [c, d] = p1;
^
structuredBinding.cpp:19:8: error: expected initializer before ‘[’ token
structuredBinding.cpp:21:2: error: ‘c’ was not declared in this scope
c += 50;
^
structuredBinding.cpp:22:2: error: ‘d’ was not declared in this scope
d += 50;
^
The book assumes its example exercise to work, but it doesn't.
I found some other topics regarding this or similar errors but none of them seem to work for me.
I also looked up the errata but there is no error registered for that part of the book.
I'm on Linux (Xubuntu) and I compile with g++ -std=c++17 -o <outputname> <inputname.cpp>
Can someone tell me what is wrong here? I would then report that error to the author.