Here’s the statement in question:
Vec3 v = (2,3,0)
After running it, v is set to (0,0,0) – can you spot why?
In case you couldn’t, here’s what happens. C++ encounters
(0,3,0) and evaluates to
0 – because comma-separated expressions evaluate left-to-right and return the rightmost expression. That’s strike one right there – the comma operator is a completely useless leftover from the days of C and gets silently applied. I’ve never seen a case where the comma operator actually was the intent of the programmer and useful in any way except to obfuscate the code.
Next strike against C++ is that I’m trying to initialize a vector here – which would have required curly braces, not parentheses. But even if I had gotten that right, there’s a good chance it fails – if Vec3 has any constructors (even empty ones), this assignment would be a syntax error.
But back to the problem at hand. The expression now boiled down to
Vec3 v = 0;
Now, clearly my vector class doesn’t allow alignment of a scalar. So what the heck is going on? That’s right – there is a convenience constructor that takes a single scalar and assigns it to all three components of the vector. Yes, it should have been marked as
explicit. Which is yet another example of C++ defaulting to the more dangerous choice. (And really, in a code base maintained by more than one person, this will always be a problem)
Why, thank you, C++. I’ll never understand how anybody could call this language type-safe. In this simple statement, it has
implicitly converted a list of integers to an integer
promoted that (silently, of course) to a float
created a vector from that, again silently
At last count that’s four different types of data that have been used interchangeably. Yes, as an experienced C++ developer you find those gotchas quickly – but I’m really getting tired of having to suffer just because of an ill-conceived language. (Yes, I know why C++ does what it does here, what the design reasons were, etc. I read the ARM. It’s still a crappy result)