C++

C language beginner's basic tutorial judgment


(1)

Write a program first:

#include <stdio.h>

int main()
{
  if(1)
  {
    printf("The condition is true!\n");
  }

  return 0;
}

Operation results:

The condition is true!

Then I changed the 1 to 2,5,100, -10, and found that the result was exactly the same. If I change it to if(0), I will find that there is no result, indicating that the printf() statement has not been executed.

The C language takes as true any non-zero or non-null value in the judgment statement. So if(1), if(2), if(5), if(100), if(-10) have the same effect.

(2)

Write another program:

#include <stdio.h>

int main()
{
  int a = 100;
  if(a > 0)
  {
    printf("The condition value is %d\n", (a > 0));
  }

  return 0;
}

Operation results:

The condition value is 1

Analysis: a = 100, a > 0 is true, so if(a) > 0) is the same thing as if of 1. In C, the judgment statement has a value of either 1 or 0. For example, a in this program > The value of 0 is 1.

(3)

Finally, write a program:

#include <stdio.h>

int main()
{
  char c1 = '\0';
  if(c1)
  {
    printf("The condition is true!\n");
  }
  else
  {
    printf("The condition is false!\n");
  }

  char c2 = ' ';
  if(c2)
  {
    printf("The condition is true!\n");
  }
  else
  {
    printf("The condition is false!\n");
  }

  char c3 = 'A';
  if(c3)
  {
    printf("The condition is true!\n");
  }
  else
  {
    printf("The condition is false!\n");
  }

  return 0;
}

Operation results:

The condition is false!
The condition is true!
The condition is true!

Note: C USES ‘\0’ to represent empty characters. The space ’ ‘is also one character, as you can see from the if(c2) condition that it is true.