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 it is 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. Why is the compiler only showing me a warning in the first program, but not showing an error?
I think that there isn't any such operator as '=', so in my case the code mustn't run, but why is there only a warning, not an error?
The 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;
}
}
}
The 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 Code::Blocks and the MinGW compiler
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.