[英]What happens inside of this condition statement? while (a = foo(bar))
聽起來可能很傻,但是我想知道在執行while(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;
};
語法說:
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語言中, 即使賦值也是一個expression ,所以您可以編寫:
a = b = c;
甚至:a = b = c = d;
但是,由於賦值也是表達式,您甚至可以編寫:
while ( a = b = c = d) { ... }
=
值等於將變量設置為的值,因此,如果執行類似
var = 0
它的值為0,如果在while循環中會中斷。
還請記住, NULL
只是0(盡管不能保證),所以返回NULL
某些東西具有相同的效果,可以打破循環。 通常,使用=
作為條件不是一個好主意,好的編譯器會警告您。
除非在系統/編譯器上另外指定,否則Null應該為零。 因此,循環終止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.