为什么在以下情况下使用赋值运算符而不是等于运算符有效?

she*_*uka 1 c if-statement selection conditional-statements

您应该有一个条件,该条件应评估为真或假,以使if语句起作用。我不明白p=fopen("test.txt", "r")以下代码的一部分如何计算为真或假,因为它只包含一个赋值运算符=而不是一个==运算符。

#include <stdio.h>
int main()
{
  FILE *p;
  if(p=fopen("test.txt","r"))
  {
      printf("yes\n");
  }
  else
    printf("no\n");
  return 0;
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 5

C11规范,第 6.5.16 章,

" 赋值表达式具有赋值后左操作数的值 [....]"

所以基本上,你的代码与

p=fopen("test.txt","r");
if(p) {  // or, if (p != NULL) for ease of understanding
 // do something

 }
Run Code Online (Sandbox Code Playgroud)