A Nifty Little Test

When I teach C programming, I’m careful to admonish beginners about the difference between the = (assignment) and == (is equal to) operators. Yet there are times when these two operators collaborate.

The single equal sign is the assignment operator, used in expressions to set a value:

a = 32;

All too often, this operator is mistakenly used as a comparison:

if(a=32)

Most compilers flag this operation with a warning. Yep, you probably meant to write:

if(a==32)

Still, the improper format does result in a comparison. The expression a=32 evaluates to 32, or whatever the assignment. In the world of C, 32 is a TRUE value, so the evaluation is TRUE.

The expression a==32 also results in a value, either 1 or 0 for TRUE and FALSE, respectively. This result is fully assignable, which you may find used in code.

2024_02_03-Lesson.c

#include <stdio.h>

int main()
{
    int a,b,c;

    a = 7; b = 7;

    c = a==b;
    printf("%d==%d = %d\n",a,b,c);

    return 0;
}

In this code, the values of variables a and b are compared. The result of the comparison is assigned to variable c. The output shows which value is generated when two variables compare equally:

7==7 = 1

If you assign -7 to variable b, the output changes:

7==-7 = 0

This code proves that the result of a comparison operation is either one or zero, TRUE or FALSE. This assign is often used in code to test and store the result of a comparison. It allows you to use the result multiple times. Or you could use the value immediately. For example:

return(a==b);

The above statement returns either one or zero, depending on the values of variables a and b. It’s a clever approach to what would otherwise be written:

if( a==b )
    return(1);
else
    return(0);

Either approach works and generates the same result, but return(a==b) is clever and will impress others who read you code.

Leave a Reply