Summary

1) Constant is a concept relative to variable; The value of a variable can be changed at any time; the value of a constant cannot be changed.

2) Constant types in C include:

  • literal: Symbol that directly denotes the meaning of a value, e.g., 5, ‘a’, “Delphi”
  • Macro constant: A symbol that indirectly denotes a value by #define, as in #define FIVE 5
  • Enumerated constants: A symbol that indirectly represents a value, as defined by enum, e.g. FIRST-> 1

3) How to define constants in C:

  • Use #define to define macros and constants
  • Enum constants are defined by enum

4) Constants are defined in C:

  • Macro constant: #define NAME Value

    • Example 1: #define MyString”Bryson”
    • Example 2: #define MyId 1
  • Enumeration constants: #define NAME Value

    • Example:
    Enum {thirdValue = 333, fourthValue = 444,}

5) Constant type:

  • Literals have default types, for example, the default type of “1” is int, and the type of “Hello World “is const char*
  • #defineThe macros and constants defined can beAny type
  • enumEnumeration constants defined can onlyplastic

6) Read-only variables in C language

  • The C language providesA const keyword that modifies a variable
  • A variable that is const can only be used as an rvalue

    • We cannot change the value of a const variable directly through the assignment operator
    • A variable modified by const is not a true constant

In C, const modifies a variable. It looks like a constant, behaves like a constant, but is essentially a read-only variable. It cannot be changed directly (by “=”), but it can be changed indirectly (by using a pointer to the address). Again, note that they are read-only variables in nature and are memory hogs. As follows:

const int a = 1; a = 2; // error, assignment of read-only variable 'a' int* p = (int*)&a; // take address *p = 2; Printf ("%d\n", a); / / 2

The other:

  • inThe C languageUnder the GCC compiler, the value of a in the code above is changed to 2. Const defines a read-only variable.
  • inC + + languageUnder the g++ compiler, the value of code a as above is still 1. Because in C++ const is defined as a constant! A is going to be placedThe symbol tableIn the. The pointer p actually modifies a portion of memory, and modifies that portion of memory to 2, so it prints a to 1 and *p to 2. (See C++ later)

This paper is summarized from the “C Language Introduction Course” by Tang Zuolin, teacher of “Ditai Software College”. If there are mistakes or omissions, please correct.