0

if (argc != 2 && argc != 3)

In my understanding how this can be possible that argc!=2 and argc!=3. If there is "or" then I can understand. How this code works.

2

Yes, it's a little mind bending. Hopefully some abstraction can help.

if (true) {quit the program}  
otherwise {run the program}

The program is only accepting 2 or 3 arguments. It seems obvious that if the number of arguments is not 2 or not 3, you want to quit the program. What happens if we substitute that perfectly good (human) logic into the program?

if (argc !=2 || argc !=3) {quit the program}
otherwise {run the program}

The if clause will always evaluate to true, even when argc is 2 or 3, because true || false evaluates to true. If argc is 2, it evaluates to true because argc !=3 is true. If argc is 3, it evaluates to true because argc !=2 is true. Therefore it always quits the program.

That's why this way if (argc != 2 && argc != 3) works.

If argc == 2, it evaluates to false because argc !=2 is false.
If argc == 3, it evaluates to false because argc !=3 is false.
Every other value of argc evaluates to true.

You must log in to answer this question.

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