Assignment Operators

suggest change

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;      /* Initialization, not an assignment expression. x holds 5. */
char y = 'c';   /* y holds the value of 'c' (99 in ASCII). */
float z = 1.5f; /* z holds 1.5. The f suffix gives the constant type float. */
char const *s = "foo"; /* s holds the address of the first character of "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 left-hand operand (a) is evaluated only once. For example, 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 and then assigns that result to a. Assignment operators associate right to left, so the rightmost assignment is evaluated first.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents