C++

Constants and variables in the C language basics tutorial


Write the program first:

#include <stdio.h>

int main()
{
  int a = 1;
  printf("a = %d\n", a);
  a = 2;
  printf("a = %d\n", a);

  return 0;
}

Operation results:

a = 1
a = 2

Program analysis:

int a = 1;

An integer variable a is defined, and 1 is assigned to a. Note that the equal sign in C is for assignment, which assigns a constant to a variable so that the variable gets a temporary fixed value. Why is it temporary? Because when you assign another constant, 2, to a, a becomes 2, not 1. Note that a = 2 is not supposed to be int a = 2. The first time you define a variable, write out the type of the variable (int type, for example). The next time you use the variable, just use it instead of redefining it. To add a type is to redefine it; to not add a type is to use it directly.

As you can see from the program, the first value of a is 1, and the second value is 2. You can see that the value of a is variable, so a is called a variable. Accordingly, 1, 2, A and B are all fixed values, which are called constants.