Assigns the value of the right-hand operand to the storage location named by the left-hand operand, and returns the value.
int x = 5; /* Variable x holds the value 5. Returns 5. */
char y = 'c'; /* Variable y holds the value 99. Returns 99
* (as the character 'c' is represented in the ASCII table with 99). */
float z = 1.5; /* variable z holds the value 1.5. Returns 1.5. */
char const* s = "foo"; /* Variable s holds the address of the first character of the string 'foo'. */
Several arithmetical operations have a compound assignment operator.
a += b /* equal to: a = a + b */
a -= b /* equal to: a = a - b */
a *= b /* equal to: a = a * b */
a /= b /* equal to: a = a / b */
a %= b /* equal to: a = a % b */
a &= b /* equal to: a = a & b */
a |= b /* equal to: a = a | b */
a ^= b /* equal to: a = a ^ b */
a <<= b /* equal to: a = a << b */
a >>= b /* equal to: a = a >> b */
One important feature of these compound assignments is that the expression on the left hand side (a) is only evaluated once. E.g if p is a pointer
*p += 27;
dereferences p only once, whereas the following does so twice.
*p = *p + 27;
It should also be noted that the result of an assignment such as a = b is what is known as an rvalue. Thus, the assignment actually has a value which can then be assigned to another variable. This allows the chaining of assignments to set multiple variables in a single statement.
This rvalue can be used in the controlling expressions of if statements (or loops or switch statements) that guard
some code on the result of another expression or function call. For example:
char *buffer;
if ((buffer = malloc(1024)) != NULL)
{ /* do something with buffer */
free(buffer);
}
else
{ /* report allocation failure */ }
Because of this, care must be taken to avoid a common typo which can lead to mysterious bugs.
int a = 2; /* ... */
if (a = 1) /* Delete all files on my hard drive */
This will have disastrous results, as a = 1 will always evaluate to 1 and thus the controlling expression of the if statement will always be true (read more about this common pitfall here). The author almost certainly meant to use the equality operator (==) as shown below:
int a = 2; /* ... */ if (a == 1) /* Delete all files on my hard drive */
Operator Associativity
int a, b = 1, c = 2;
a = b = c;
This assigns c to b, which returns b, which is than assigned to a. This happens because all assignment-operators have right associativity, that means the rightmost operation in the expression is evaluated first, and proceeds from right to left.