Anon
Anon

Reputation: 2656

Output of this C program

What should be the output of this C program?

int main()
{
    int x=1,y=1,z;
    if (z=(y>0)) x=5;
    printf("%d %d",x,z);
    return 0;
}

As expected, the output is X is 5 and Z is 1. This is because when expression y>0 is evaluated it is true and so on and so forth. Now the problem is in this program:

int main()
{
    int x,y;
    for (y=1;(x=y)<10;y++)
    ;

    printf("%d %d",x,y);
    return 0;
}

should not the output be an infinite loop? Reason being, (x=y) will always return true(1), which is always less than 10?

Upvotes: 1

Views: 149

Answers (3)

dee-see
dee-see

Reputation: 24078

x = y is an assignment, you're confusing it for x == y. What actually happens is that x takes y's value and then it's compared to 10 until the < 10 condition stop being true.

And in your example, y == 1 (initially) and x is no initialized so x == y would not necessarily be true.

Upvotes: 2

Flame
Flame

Reputation: 2207

The reason is because at some point y evaluatess to 10 is assigned to x. The value of the assignment is 10 therefore not less than 10. The loop terminates.

Upvotes: 2

Delan Azabani
Delan Azabani

Reputation: 81384

No, (x=y) returns the new value after setting x to y's value.

However, (x==y) returns 1 if they are equal, and 0 if not.

Upvotes: 7

Related Questions