C: transitive (double) assignments

后端 未结 6 1227
半阙折子戏
半阙折子戏 2021-01-20 07:11

I have used such construct in C:

list->head = list->tail = NULL;

and now I consider whether this really mean what I suppose.

<
6条回答
  •  遇见更好的自我
    2021-01-20 07:36

    Associativity of assignment operator = is right to left. This means that if there are more than one = operator in a statement, then the rightmost is evaluated first, then the one left to it, and in that order, untill the leftmost = operator is evaluated at last.

    This means that when you do

    list->head = list->tail = NULL;
    

    the right most assignment, i.e. list->tail = NULL is evaluated first. So list->tail will be NULL.

    After that list->head = list->tail will be evaluated. And since list->tail is NULL by now (because of previous evaluation- i.e. list->tail = NULL), now list->head is also NULL.

    Based on how you are representing in your question, it is like

    list->tail = NULL; list->head = list->tail;
    

提交回复
热议问题