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

Viewed 132

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!

3 Answers

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.

From the C Standard (6.5.3.3 Unary arithmetic operators ¶5)

5 The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

So according to the quote the if statement

if (!(a=10)) {

is equivalent to

if ( ( a = 10 ) == 0 ) {

As the value of the assignment sub-expression, a = 10 is equal to 10 that is it is not equal to 0 then the condition of the if statement evaluates to logical false and the sub-statement of the if statement will not get the control and you will have an infinite while loop.

In fact, you can rewrite this while loop

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

the following way with the same effect

  while ( ( a = 10 ) ) {}

or just

  while ( ( a = 10 ) );

or more simply:

while ( a != 0 );

because what is important is that within the while loop the variable a does become equal to 0.

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

as !(a = 10) is always zero (false) it is equivalent of:

      while (1) {
      }
Related