Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an assignment return?

Tags:

c

Why does an expression i = 2 return 2? What is the rule this is based on?

printf("%d\n", i = 2 ); /* prints 2 */

I am in C domain after spending long time in Java/C#. Forgive my ignorance.

like image 617
Nemo Avatar asked Mar 01 '12 10:03

Nemo


People also ask

What does an assignment return in Java?

The assignment operator in Java evaluates to the assigned value (like it does in, e.g., c). So here, readLine() will be executed, and its return value stored in line . That stored value is then checked against null , and if it's null then the loop will terminate.

What does an assignment statement return in C++?

It assigns value to t variable (and in your code t is reference type so the change is visible outside), and then return value of t variable.

What is the purpose of an assignment statement?

An assignment statement sets the current value of a variable, field, parameter, or element. The statement consists of an assignment target followed by the assignment operator and an expression. When the statement is executed, the expression is evaluated and the resulting value is stored in the target.


1 Answers

It evaluates to 2 because that's how the standard defines it. From C11 Standard, section 6.5.16:

An assignment expression has the value of the left operand after the assignment

It's to allow things like this:

a = b = c; 

(although there's some debate as to whether code like that is a good thing or not.)

Incidentally, this behaviour is replicated in Java (and I would bet that it's the same in C# too).

like image 192
Oliver Charlesworth Avatar answered Oct 02 '22 10:10

Oliver Charlesworth