【发布时间】:2018-03-12 06:20:40
【问题描述】:
我正在为我的 CS 课程阅读计算机系统,我遇到了一个令我困惑的 while 循环条件,这是代码:
int parseline(char *buf, char **argv)
{
char *delim; /* Points to first space delimiter */
int argc; /* Number of args */
int bg; /* Background job? */
buf[strlen(buf)-1] = ’ ’; /* Replace trailing ’\n’ with space */
while (*buf && (*buf == ’ ’)) /* Ignore leading spaces */
buf++;
/* Build the argv list */
argc = 0;
while ((delim = strchr(buf, ’ ’))) {
argv[argc++] = buf;
*delim = ’\0’;
buf = delim + 1;
while (*buf && (*buf == ’ ’)) /* Ignore spaces */
buf++;
}
在
while (*buf && (*buf == ’ ’)) /* Ignore spaces */
while 循环有两个逻辑操作数&&,但我不明白第一个操作数(*buf) 的用途是什么。第二个操作数正在检查空白空间,但我认为第二个操作数本身就足以满足此循环的目的。
【问题讨论】:
-
如果 buf == NULL 会发生什么?我尝试使用 buf == NULL 运行简化版本的代码并出现段错误,因为据我猜测,循环条件试图尊重 NULL 指针。在循环条件中有一个指针是不好的编程习惯吗?是否应该使用带有标志条件的循环?
-
buf在此之后不能是NULL:buf = delim + 1;
标签: c while-loop