C++ learning the difference between character constants, string constants and symbolic constants

Character constant

Character constants are enclosed in a character 单引号.
Note:

  • Character constants can only contain one character, such as 'AB', which is illegal
  • Character constants are case sensitive
  • The single quote " ' " is a delimiter and not part of a character constant

String constant

String constants are enclosed 双引号character sequences.
Example: "abc"
is actually stored as:
Insert image description here

Note:

  • The system will automatically add a null character '\0' at the end of the string as the terminator of the string, so the storage length of each string is 1 more than the actual length.
  • '\0' is not part of the string, it only serves as the end mark of the string
  • Only the number of characters in the character sequence enclosed by double quotes is called the string length
  • In addition to the different quotation marks used, the most important difference between string constants and character constants is the different storage forms.
  • The escape character appears to be multiple characters, but in reality it represents only one character.

symbolic constant

In order to make it easier to read the code, in C++ programming, a symbolic name is often used to represent a constant, which is called a symbolic constant. That is, give this constant an identifier. In subsequent references, we directly use this identifier to represent the constant.
Symbolic constants must be defined before use, and are generally defined before the main function. The definition format is as follows:

# define 符号常量 常量

Example:

#include<iostream>
using namespace std;
# define PRICE 30  /*注意这不是语句,末尾不要加分号*/
int main(){
    
    
	cout<<"price="<<PRICE<<endl;
	return 0;
}

Note:

  • Symbolic constants are different from variables. Its value cannot be changed within its scope, nor can it be assigned
  • It is customary to use uppercase English identifiers for symbolic constant names, and lowercase English identifiers for variable names to show the difference.
  • The purpose of defining symbolic constants is to improve the readability of the program and facilitate program debugging and modification.
  • For strings enclosed in double quotes in the program, even if they are the same as symbols, they will not be replaced during preprocessing.

Guess you like

Origin blog.csdn.net/David_house/article/details/130548836