Search code examples
ccomparecomparison

why usage of '&&' operator have different meaning with '=' and with'=='


I was looking at MIT assignments and found this question below link problem 2.5) option B)

Practical Programming in C - MIT (PDF)

Now it says

Assume (x=0,y=0,alliszero=1). alliszero =(x=1) && (y=0);

they are just asking to find statement will give error or not. And in solution they are saying

’=’ operator should be replaced with ’==’. The correct version is alliszero =(x==1) && (y==0);

consider below program

#include <stdio.h>
int main()
{

    int x =0 , y = 0 , alliszero =1;
    alliszero = (x = 1) && (y = 0);
    printf("%d",alliszero);

}

Now after I run this program then I am getting output as 0, But above they mentioned it as error, I am understanding that it should be running fine, then what is happening that they are saying it will give error, does they mean by different context?


Solution

  • Given the explicitly stated circumstances, there is no error in alliszero =(x=1) && (y=0);. This code is well-defined by the C standard, presuming there are suitable declarations for x, y, and alliszero. It says to assign 1 to x and, if that is true (which it is), to assign 0 to y, then assign the result of 1 && 0 to alliszero.

    However, there are implicit requirements. The author of this exercise intended the student to recognize that the code alliszero =(x=1) && (y=0); was intended, by some hypothetical programmer, to test whether x is 1 and y is 0, rather than to assign values. In this case, operators for testing equality, rather than for assigning values, should be used. The = operator assigns a value; the == operator tests whether two operands are equal. Given this assumption about the intent, the code should be alliszero = (x == 1) && (y == 0);.

    This is a bad exercise because its author does not give any criteria by which the code can be judged to be wrong. This is fundamental to software engineering:

    A bug is a deviation from specification.

    In other words, a program is wrong if and only if it differs from what it is specified to be. There should be an explicit statement saying what a program should do. Without a specification, it cannot formally be said there is a bug. This is a simple yet effective tool: Always know what your program is supposed to be, and that provides you mechanisms for testing for bugs, examining the program to find bugs, and more.

    In this case, the exercise author could have included a statement such as “alliszero should be set to 1 iff x is 1 and y is 0.” Experienced programmers can recognize this code as erroneous because they have seen novice programmers make such mistakes, and likely made such mistakes early in their studies, and because it uses a complicated expression to assign a constant value to alliszero. The result of (x=1) && (y=0) will always be zero, so it is suspicious to use this complicated code instead of x = 1; y = 0; alliszero = 0;.