这可能听起来很愚蠢,但我想知道我执行时发生的事情(a = function(b)){}。
假设我们为read_command_stream的返回值获取了NULL。
我可以退出循环吗?
while ((command = read_command_stream (command_stream)))
{
if (print_tree)
{
printf("# %d\n", command_number++);
print_command (command);
}
else
{
last_command = command;
execute_command(command, time_travel);
}
}
struct command
{
enum command_type type;
// Exit status, or -1 if not known (e.g., because it has not exited yet).
int status;
// I/O redirections, or null if none.
char *input;
char *output;
union
{
// for AND_COMMAND, SEQUENCE_COMMAND, OR_COMMAND, PIPE_COMMAND:
struct command *command[2];
// for SIMPLE_COMMAND:
char **word;
// for SUBSHELL_COMMAND:
struct command *subshell_command;
} u;
};
答案 0 :(得分:3)
语法说:
while (expression) { ... }
和expression
可以很多。
它可以是:
while (1) { ... }
while (a < b) { ... }
while (a < b && c < d ) { ... }
while (*dst++ = *src++) {;}
while((ch = getc()) != EOF) { ... }
while(i) ( ...)
while (i--) { ... }
(即使有副作用!)while (*++argv) { ... }
现在,在整数表达式的情况下,检查表达式不等于零。对于指针表达式,将检查不等于NULL 。就是这样。
关键在于,在C中,即使作业是一个表达,所以你可以写:
a = b = c;
甚至: a = b = c = d;
但是,由于作业也是表达式,你甚至可以写:
while ( a = b = c = d) { ... }
答案 1 :(得分:1)
=
评估它设置变量的内容,所以如果你做了类似的事情
var = 0
这个计算结果为0,如果它在while循环中会爆发。
另外请记住NULL
只是0(虽然不能保证)所以返回NULL
的东西会产生相同的效果来打破循环。一般来说,使用=
作为条件是一个坏主意,好的编译器会警告你。
答案 2 :(得分:0)
除非系统/编译器另有指定,否则Null应该为零。因此,循环终止。