Reputation: 3787
The ++
and --
operators are included in many other languages. Why did the language designers choose not to include these operators in Rust?
Upvotes: 6
Views: 2717
Reputation: 3787
They are not included in Rust as they can lead to subtle bugs because they require complex knowledge about evaluation order, especially when combined into larger expressions as shown below. Can you guess what these two C++ programs print? I guessed wrong.
#include <cstdio>
int main()
{
int a = 4;
int b = 4;
int c = a++ + b++;
printf ("%i %i %i", a, b, c);
return 0;
}
#include <cstdio>
int main()
{
int x = 10;
int z = ++x + x++;
printf ("%i %i", x, z);
return 0;
}
From the FAQ:
Why doesn't Rust have increment and decrement operators?
Preincrement and postincrement (and the decrement equivalents), while convenient, are also fairly complex. They require knowledge of evaluation order, and often lead to subtle bugs and undefined behavior in C and C++. x = x + 1 or x += 1 is only slightly longer, but unambiguous.
Upvotes: 12