Node:Hidden assignments, Next:, Previous:Hidden operators and values, Up:Hidden operators and values

Hidden assignments

Assignment expressions have values too -- their values are the value of the assignment. For example, the value of the expression c = 5 is 5.

The fact that assignment statements have values can be used to make C code more elegant. An assignment expression can itself be assigned to a variable. For example, the expression c = 0 can be assigned to the variable b:

b = (c = 0);

or simply:

b = c = 0;

These equivalent statements set b and c to the value 0, provided b and c are of the same type. They are equivalent to the more usual:

b = 0;
c = 0;

Note: Don't confuse this technique with a logical test for equality. In the above example, both b and c are set to 0. Consider the following, superficially similar, test for equality, however:

b = (c == 0);

In this case, b will only be assigned a zero value (FALSE) if c does not equal 0. If c does equal 0, then b will be assigned a non-zero value for TRUE, probably 1. (See Comparisons and logic, for more information.)

Any number of these assignments can be strung together:

a = (b = (c = (d = (e = 5))));

or simply:

a = b = c = d = e = 5;

This elegant syntax compresses five lines of code into a single line.

There are other uses for treating assignment expressions as values. Thanks to C's flexible syntax, they can be used anywhere a value can be used. Consider how an assignment expression might be used as a parameter to a function. The following statement gets a character from standard input and passes it to a function called process_character.

process_character (input_char = getchar());

This is a perfectly valid statement in C, because the hidden assignment statements passes the value it assigns on to process_character. The assignment is carried out first and then the process_character function is called, so this is merely a more compact way of writing the following statements.

input_char = getchar();
process_character (input_char);

All the same remarks apply about the specialized assignment operators +=, *=, /=, and so on.

The following example makes use of a hidden assignment in a while loop to print out all values from 0.2 to 20.0 in steps of 0.2.

#include <stdio.h>

/* To shorten example, not using argp */
int main ()
  double my_dbl = 0;

  while ((my_dbl += 0.2) < 20.0)
    printf ("%lf ", my_dbl);

  printf ("\n");

  return 0;