ILWC Privacy Statement About ILWC
Registreer
134
another short one on if then else
martijn
c
2019-02-28 18:40:58
2019-02-28 19:00:00
2019-03-28 19:00:00
What counts as true and what counts as false whitin c?
Let's find out.

First let me show you a little demo program:
#include 

 

int main(int argc, char ** argv){

  int a=10;

  if (a==10)
    printf("True\n");
 

  else
    printf("False\n");

  if (a)
    printf("True\n");
  else
    printf("False\n");

  if (a-10)
    printf("True\n");
  else
    printf("False\n");

    if (a-11)
    printf("True\n");
  else
    printf("False\n");

  return 0;
}

  1. The first if says a==10. This is true since I assigned a the value 10. So I expect the ouput to read "True".
  2. The second if just says a (which is 10). Is 10 true or is 10 false? We will see when we run the program.
  3. The third if tests for a-10 (is 0 (a-10=>10-10=0)). Is 0 true or is 0 false? We will see when we run the program.
  4. And then, what is the result for a-11 (is -1 (a-11 => 10-11=-1)). Is -1 true or is -1 false? We will see when we run the program.

Let's compile the progam:
[martijn@radijs misc]$ gcc -o if if.c
[martijn@radijs misc]$
No problems here...

And then run it:
[martijn@radijs misc]$ ./if 
True
True
False
True
[martijn@radijs misc]$
  1. Our prediction is true. a==10 => 10==10 is actually true...so the output is "True"
  2. The second if apparently is alsotrue. so a positive integer (not zero) is true
  3. The third test results in false. a-10 => 10-10=0. Apparently 0 is false in this respect.
  4. And finally a negative number results in True.
In short....only 0 will result in False. All other values result in True.