2

I'm having some confusion on Pset3. In the program "generate.c" there is an "if" condition for validating the argument counts. Here is the portion I'm having confusion :

if (argc != 2 && argc != 3)
{
    printf("Usage: generate n [s]\n");
    return 1;
}

We know that, the logical "AND" operator became true only when both side of "AND" became true. My confusion here is, "argc != 2" became true only when arguments counts are not equals to two. Also "argc != 3" became true only when argument counts are not equals to three. But how both of them became true at the same time? Either one of them should be false when another is true.

Please help me to understand where I am missing the point.

5

It can be confusing, but easily explained with an example.

Let's say that argc = 4.

Well, 4 does not equal 2 AND 4 does not equal 3. Therefore the condition is TRUE.

The condition is only false when argc == 2 OR argc == 3.

This could have also been written as if( !(argc == 2 || argc == 3) )

The idea of the condition is this: when argc isn't 2 or 3, print out a message that shows correct usage of the program. The code actually wants the condition to fail, to be false, to run the rest of the program.

Also remember that if any part of an AND is false, the whole thing is false and you don't need to check the rest. So, as soon as it sees that argc is 2 or is 3, the condition is false.

(That's actually how code gets optimized. It will evaluate left to right. As soon as a condition is found that fails, evaluation stops and the test is failed. For example, look at this: IF( a!=0 && (b/a) > 1) {do something} If a is zero, the condition fails without evaluating the second part. If that test weren't there and it was written as if( (b/a > 1 ), division by zero would present a serious problem.)

1
  • Thank you very much, now its clear to me. Apr 28 '15 at 4:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .