C语言的一些奇技淫巧(1)嵌套语句
1.嵌套语句/复合语句
1.1 例子 for(i=0; i<3 && ({j=1;TRUE;}); i++)
此句中, i<3 && ({j=1;TRUE;}); 是一个语句,
后面 ({j=1;TRUE;}) 是一个复合语句
这句无论j=1 怎么变,都是最后一句 TRUE 为真。
所以真正的还是前面i<3 成立即可
2. list_for_each_safe() 源码例子
/**
* list_for_each_safe - iterate over a list safe against removal of list entry
* @pos: the &struct list_head to use as a loop counter.
* @n: another &struct list_head to use as temporary storage
* @head: the head for your list.
*/
源码:
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); \
pos = n, n = pos->next)
修改如下:
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next; (pos != (head) && ( { n = pos->next;TRUE; } ) ); \
pos = n, n = pos->next)
- 重点: (pos != (head) && ( { n = pos->next;TRUE; } )
这是一个复合语句,后面总是true,为了让本次循环只要前面true就执行下去
遍历时用n 接住下一个节点,防止pos 删除操作导致找不到节点了