簡體   English   中英

此條件聲明內部會發生什么? 而(a = foo(bar))

[英]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命令

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM