3 ms·
What would you expect that to do instead? C++ doesn't have multiple assignment.
by chrisseaton 6y ago
What would you expect that to do instead? C++ doesn't have multiple assignment.
- phoe-krk 6y agoC++17 is capable of multiple variable declaration, which is a similar concept. #include <tuple> #include <iostream> std::tuple<int, int> divide(int dividend, int divisor) { return {dividend / divisor, dividend % divisor}; } int main() { using namespace std; auto [quotient, remainder] = divide(14, 3); cout << quotient << ',' << remainder << endl; }
- amelius 6y agoYes, the code auto [quotient, remainder] = divide(14, 3); is not an assignment. In an assignment, you should write something like std::tie(quotient, remainder) = divide(14, 3); which is a tuple assignment written as a single assignment. This shows the kind of (imho) "ugly hacks" the C++ committee had to make to cover up the historical mistake with the comma operator.
- amelius 6y agoWell, the situation is even trickier: (a, b) = (10, 20) is allowed code in C++ (not in C). The result is that 20 is assigned to b, and a is untouched. Contrast this to: a, b = 10, 20 where (as above) 10 is assigned to b and a is left untouched, because it is parsed as: a, (b = 10), 20 and I hope you agree that the behavior is very confusing.
- rini17 6y agoSuch misleading code should trigger an error.
- phoe-krk 6y agoNot really an error, since it is syntactically valid C++. It could definitely trigger a compiler warning, though.
- rini17 6y agoCode that violates C++ static typing rules can be syntactically valid too, yet noone is proposing it should be only a warning. (I find this the most weird thing about C/C++ culture: they are so proud it is static typed, yet oblivious to all the other problems and traps/memory unsafety/undefined behavior/etc.)