Search code examples
cvariable-assignmentassignment-operatorboolean-operations

What does the line "h = b = out" mean in C


 h = b = out;

 /* h is the number of code points that have been handled, b is the  */
 /* number of basic code points, and out is the number of ASCII code */
 /* points that have been output.                                    */

I can't figure out whether this line is just a weird way of setting both h and b equal to out OR if it's a boolean expression that sets h equal to true (0?) if b is already equal to out.


Solution

  • = is always the assignment operator in C and can't be used for comparing 2 values. To get a "boolean" expression you must use ==. The expression a = b assigns b to a and also returns the assigned value that can be used in another expression. So h = b = out; actually assigns out to both b and h. It's parsed as h = (b = out) because in C the = operator is left associative

    Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non-lvalue (so that expressions such as (a=b)=c are invalid).

    https://en.cppreference.com/w/c/language/operator_assignment