user10370213
user10370213

Reputation:

How come this code prints "yes" even though there is an assignment and not comparison operator in the following code

There is an assignment operator in the if condition and when executed it prints "yes" as output. I didn't get it.

#include<stdio.h>

int main()
{
    float f = 0.1;

    if (f=0.1)
    {
        printf("Yes");
    }
    else 
    {
        printf ("no");
    }
}

Upvotes: 0

Views: 81

Answers (1)

Aconcagua
Aconcagua

Reputation: 25546

The assignment operator has a result, it is the variable that just has been assigned!

So the code actually is equivalent to:

f = 0.1;
if(f) // and as unequal to 0...

You can try to assign 0.0 for comparison:

if(f = 0.0)

Now it will print no.

Upvotes: 4

Related Questions