Node:The assignment operator, Next:Expressions and values, Previous:Expressions and operators, Up:Expressions and operators
The assignment operator
No operator such as addition (+
) or multiplication (*
)
would be useful without another operator that attaches the values they
produce to variables. Thus, the assignment operator =
is perhaps
the most important mathematical operator.
We have seen the assignment operator already in our code examples. Here
is an example to refresh your memory:
int gnu_count, gnat_count, critter_count; gnu_count = 45; gnat_count = 5678; critter_count = gnu_count + gnat_count;
The assignment operator takes the value of whatever is on the right-hand
side of the =
symbol and puts it into the variable on the
left-hand side. For example, the code sample above assigns the value 45
to the variable gnu_count
.
Something that can be assigned to is called an lvalue,
("l" for "left", because it can appear on the left side of an
assignment). You will sometimes see the word lvalue
in error
messages from the compiler. For example, try to compile a program
containing the following code:
5 = 2 + 3;
You will receive an error such as the following:
error-->
bad_example.c:3: invalid lvalue in assignment
You can't assign a value to 5; it has its own value already! In other words, 5 is not an lvalue.