2
$\begingroup$

Some languages (for example C and C++) have assignment expressions, which means the assignment statement as a whole returns a value of the object specified by the left operand after the assignment.

So for example in C++, this snippet:

int a;
std::cout << (a = 1);

will print 1.

In other languages (such as Pascal), define the assignment as a statement (meaning that it cannot be used in an expression), and there are no assignment expressions at all. Try to do writeln(a := 1111); and it will return an error.

Python takes a hybrid approach, in that it has both operators, = and the walrus operator :=, in which := is an assignment expression but = is not, so you can do print(a := 1) (link), but not print(a = 1) (link).

It's clear that each language takes a different approach to assignment expressions, so what are the pros and cons of having assignment expressions?

$\endgroup$
0

1 Answer 1

3
$\begingroup$

Assignment expressions can introduce bugs (when paired with implicit conversion)

For example, in C++, consider this snippet:

int a = 1;
if(a = 2)
{
    std::cout << "Code in here will be executed";
}

It will print the code inside the if statement, although it's not clear as to why at first glance.

Not having assignment expressions can avoid this entire class of bugs.

$\endgroup$
1
  • 1
    $\begingroup$ I fully agree that this is a problem. But there are three factors that together lead to the problem: assignment as expression, treating integers as valid booleans, and using a very similar syntax for comparison and assignment. So, you can't blame it on assignment expressions alone. $\endgroup$ Jul 7, 2023 at 10:43

Not the answer you're looking for? Browse other questions tagged .