Solution for Exercise 8-7

ex0807

#include <stdio.h>

int main()
{
    int a;

    a = 5;

    if(a=-3)
    {
        printf("%d equals %d\n",a,-3);
    }
    return(0);
}

Notes

* A variable assignment in C is always a TRUE condition. So Line 10 evaluates TRUE no matter what value is assigned to variable a.

* Modify Line 9 so that it reads:

Build and run. The output reads 5 equals -3 because the assignment is TRUE, not because the value of variable a is -3.

* The point of the exercise isn't to describe how assignments are always TRUE, but rather that you need to use two equal signs instead of one when making an "is equal to" comparison.

* The compiler may warn of the assignment a=-3 (or a=5) in the comparison. The warning message I see is "suggest parentheses around assignment used as truth value," which is probably just telling you to use two equal signs instead of one, I suppose.

* An exception to the assignment = always being TRUE is when you assign a zero value, as in:

if(a=0)

Because the value zero is assigned, the result is FALSE. Watch out for that one.