Shubham Bhandari
Shubham Bhandari

Reputation: 39

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

I am a beginner in c programming and was practicing a program to find the greatest numbers among 10 number using arrays.

So, in the first program, the compiler is issuing a warning:

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

But not an error which means that the program is running but always the number that I input is being shown as the greatest number.

The second one is running just fine and is showing correct output. So, my question is that why is the compiler only showing me a warning in the first program but not showing an error?

I think that there's no such operator as '=' so in my case the code mustn't run, but why only a warning not an error?

First program:

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

second program:

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

Note : I am using codeblocks and MINGW compiler

Upvotes: 1

Views: 168

Answers (2)

anastaciu
anastaciu

Reputation: 23792

It's not an error, = is the assignment operator, you are allowed to use the assigment operator inside an if statement.

Since it's not a common use, the compiler warns you, to verify if that is indeed what you want to do, it's not mandated to do it, but it's a safety feature.

An assignment like that, inside an if statement will always be true, except if the assigned value is 0 in which case te condition will evaluate to false.

Note that if you want to treat warnings as errors you can use -Werror flag, in fact I think it's a good idea to do so.

Upvotes: 2

Therabidpanther
Therabidpanther

Reputation: 86

Thex=9 is actually a valid operator, but it’s setting x equal to 9 every time it runs. Since there’s no real conditional statement going on though, it will result in true every time it’s ran. It will not throw an error though!

Upvotes: 0

Related Questions