在这个条件声明中发生了什么?而(a = foo(bar))

时间:2013-10-06 23:38:28

标签: c

这可能听起来很愚蠢,但我想知道我执行时发生的事情(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

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;
};

3 个答案:

答案 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应该为零。因此,循环终止。