Hacker News new | ask | show | jobs
by chrisseaton 2209 days ago
What would you expect that to do instead? C++ doesn't have multiple assignment.
3 comments

Well, 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.
C++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;
    }
Yes, 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.

Such misleading code should trigger an error.
Not really an error, since it is syntactically valid C++. It could definitely trigger a compiler warning, though.
Code 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.)