Next: , Previous: , Up: GNU C Manual   [Contents][Index]


7 Assignment Expressions

As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues) because they are locations that hold a value.

An assignment in C is an expression because it has a value; we call it an assignment expression. A simple assignment looks like

lvalue = value-to-store

We say it assigns the value of the expression value-to-store to the location lvalue, or that it stores value-to-store there. You can think of the “l” in “lvalue” as standing for “left,” since that’s what you put on the left side of the assignment operator.

However, that’s not the only way to use an lvalue, and not all lvalues can be assigned to. To use the lvalue in the left side of an assignment, it has to be modifiable. In C, that means it was not declared with the type qualifier const (see const Variables and Fields).

The value of the assignment expression is that of lvalue after the new value is stored in it. This means you can use an assignment inside other expressions. Assignment operators are right-associative so that

x = y = z = 0;

is equivalent to

x = (y = (z = 0));

This is the only useful way for them to associate; the other way,

((x = y) = z) = 0;

would be invalid since an assignment expression such as x = y is not valid as an lvalue.

Warning: Write parentheses around an assignment if you nest it inside another expression, unless that is a conditional expression, or comma-separated series, or another assignment.


Next: Execution Control Expressions, Previous: Arithmetic, Up: GNU C Manual   [Contents][Index]