为什么在以下情况下使用赋值运算符而不是等于运算符?
why using the assignment operator instead of equal to operator works in the following situation?
为了使 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;
来自 C11
规范,第 6.5.16 章,
" An assignment expression has the value of the left operand after the assignment [....]"
基本上,您的代码与
相同
p=fopen("test.txt","r");
if(p) { // or, if (p != NULL) for ease of understanding
// do something
}
如果您不使用赋值,那么 p
将包含未初始化的垃圾。通常,在条件内使用赋值运算符被认为是不好的做法(大多数编译器会警告不要这样做),因为它很危险且难以阅读。但它是完全有效的,因为 =
运算符的结果与大多数运算符一样,在本例中为 p
.
的值
所以你的例子中的代码是一种更草率、更糟糕的编写方式
p=fopen("test.txt","r")
if(p)
这又是
的草率版本
if(p != NULL)
来自 C 标准 )6.8.4.1 if 语句)
2 In both forms, the first substatement is executed if the expression
compares unequal to 0. In the else form, the second substatement is
executed if the expression compares equal to 0. If the first
substatement is reached via a label, the second substatement is not
executed.
和(6.5.16 赋值运算符)
3 An assignment operator stores a value in the object designated by
the left operand. An assignment expression has the value of the left
operand after the assignment,111) but is not an lvalue
所以表达式的值
p=fopen("test.txt","r")
是一个指针,在函数调用成功的情况下fopen
不等于0。
为了使 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;
来自 C11
规范,第 6.5.16 章,
" An assignment expression has the value of the left operand after the assignment [....]"
基本上,您的代码与
相同p=fopen("test.txt","r");
if(p) { // or, if (p != NULL) for ease of understanding
// do something
}
如果您不使用赋值,那么 p
将包含未初始化的垃圾。通常,在条件内使用赋值运算符被认为是不好的做法(大多数编译器会警告不要这样做),因为它很危险且难以阅读。但它是完全有效的,因为 =
运算符的结果与大多数运算符一样,在本例中为 p
.
所以你的例子中的代码是一种更草率、更糟糕的编写方式
p=fopen("test.txt","r")
if(p)
这又是
的草率版本if(p != NULL)
来自 C 标准 )6.8.4.1 if 语句)
2 In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0. If the first substatement is reached via a label, the second substatement is not executed.
和(6.5.16 赋值运算符)
3 An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment,111) but is not an lvalue
所以表达式的值
p=fopen("test.txt","r")
是一个指针,在函数调用成功的情况下fopen
不等于0。