Search code examples
cif-statementnegation

How would a compiler interpret `if(!(a=10))`?


I have a homework assignment in which I believe the professor has made a typo, typing if(!(a=10)) instead of if(!(a==10)). However, when asked if this was typo, she told me to "assume that the equations are correct and give your answer." Specifically, the assignment is to describe the behavior of the program:

#include <stdio.h>

int main() {
      int a = 100;
      while (1) {
          if (!(a=10)) {
              break;
          } 
      }
      return 0; 
}

If the offensive code read (!(a==10)) then the program would enter the if loop, reach the break and exit both loops, which makes sense for a beginner-level course in C programming.

However, if, truly, the code is meant to read (!(a=10)) then I don't know what the compiler will interpret that to mean. I do know that the code compiles, and when you run it in UNIX, it just allows you to input whatever you want using the keyboard, like say the number "7", and then you press enter and it moves to a new line, and you can enter "dog", and move to a new line, and on and on and it never exits back to the command line. So (1) how would the compiler interpret (!(a=10))? And (2) why does the program allow you to just continue to input entries forever?

Thanks!


Solution

  • For the first question, What's the meaning of if( !(a=10) ){break;}, It's equivalent to

    a = 10; if(!a) {break;}

    For a value of 10 !a will be 0 and it never breaks the while loop. In this particular example, if you assign if(!(a=0)), then it will exit the loop;

    For the second question, there is no code present in your example. But first question's answer can be extended here as the loop never breaks it keeps on asking the input values.