当我在 if 条件语句中使用“=”而不是“==”时,为什么我的编译器没有显示错误?

Why is my compiler not showing an error when I'm using '=' instead of '==' in if conditional statement?

我是 c 编程的初学者,正在练习使用数组在 10 个数字中找到最大数字的程序。

因此,在第一个程序中,编译器发出警告:

warning: suggest parentheses around assignment used as truth value [-Wparentheses]|

但不是错误,这意味着程序是 运行ning,但我输入的数字始终显示为最大数字。

第二个 运行ning 很好并且显示正确的输出。所以,我的问题是,为什么编译器在第一个程序中只显示警告而不显示错误?

我认为没有像“=”这样的运算符,所以在我的例子中代码不能 运行,但为什么只有警告而不是错误?

第一个节目:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int x, i;
float a [10];
printf("Enter 10 numbers: ");

for (i = 0; i<=9; i++)
    {
        scanf("%f",&a[i]);
    }

for (i =0; i<=9; i++)
    {
        x =0;
        for (int j =0; j<=9; j++)
        {
            if (a[i]>a[j])
                {
                    x++;
                }
        }

        if (x = 9)
        {
        printf("The greatest number is %f",a[i]);
        break;
        }  
    }
}

第二个节目:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int x, i;
float a [10];
printf("Enter 10 numbers: ");

for (i = 0; i<=9; i++)
    {
        scanf("%f",&a[i]);
    }

for (i =0; i<=9; i++)
    {
        x =0;
        for (int j =0; j<=9; j++)
        {
            if (a[i]>a[j])
                {
                    x++;   
                }
        }

        if (x == 9) //replaced '=' in the first program with '=='
        {
        printf("The greatest number is %f",a[i]);
        break;
        }
    }   
}

注意:我正在使用代码块和 MINGW 编译器

这不是错误,= 是赋值运算符,您可以在 if 语句中使用赋值运算符。

由于这不是常见用途,因此编译器会警告您,以验证这是否确实是您想要执行的操作,它不是强制执行的,但它是一项安全功能。

if 语句中这样的赋值将始终为真,除非赋值为 0,在这种情况下,条件将计算为假。

请注意,如果您想将警告视为错误,您可以使用 -Werror 标志,事实上我认为这样做是个好主意。

x=9实际上是一个有效的运算符,但它每次运行时都会将 x 设置为 9。由于没有真正的条件语句在进行,因此每次 运行 时都会返回 true。不过它不会抛出错误!