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

Output

-3 equals -3

Notes

* A variable assignment, such as a=-3, is a TRUE expression in the C language, unless the value assigned is zero, in which case it's FALSE. The expression in Line 10 evaluates TRUE.

* 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 evaluated, but rather to drive home that you must 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 "place parentheses around theassignment to silence this warning," which is probably just telling you to use two equal signs instead of one, I suppose.