在本節中,我們將了解更多關於c++常量和字麵量的知識。在c++中,const修飾符用於創建常量,即初始化後不能更改其值的變量。通常常量是用大寫寫的,通常放在程序文件的頂部。它的語法如下:
Const類型變量= value;const int PI = 3.14;
你不能重置常量的值。例如,當我們試圖更改常量字麵量的值時,下麵的代碼片段將給出錯誤。
#include using namespace std;Int main() {Int i,j;....const int SPEED_OF_LIGHT = 300000000;...SPEED_OF_LIGHT = 250000000 //錯誤!不能改變SPEED_OF_LIGHT,它是一個常量. ...}
另一種創建常量的方法是使用#define preprocessor指令。如。
#定義光速300000000
c++字麵量是用來表示定點值的數據,我們可以直接在代碼中使用。例如:100,3.1421,'y', 'n'等。
請注意,變量可以被賦不同的值,但文字不能。c++中有6種類型的字麵量。
- Integer literal An integer is a fixed point numeric literal. It has no fractional or exponential part. There are three types of integer literals used in C++ programming i.e. decimal (base 10), octal (base 8) and hexadecimal (base 16). Please note that octal literal starts with a 0 while hexadecimal literal starts with a 0x. For e.g.
十進製文字:-1,0,100等。
八進製文字:045,067,043等。
十六進製文字:0x8f, 0xa2, 0x721等。
Floating point literal A floating-point literal is different from integar literal as it has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point
b .十進製形式或指數形式的字麵量。十進製形式必須有小數點或指數,或兩者都有,而指數形式必須有整數部分,小數部分,或兩者都有。帶符號的指數用e或e表示。
3.14134 // Legal 314159E-5L // Legal 620E //非法:不完整指數22f //非法:沒有小數或指數。e755 //非法:缺少整數或分數
C.Boolean literal C++ has two Boolean literals i.e. true which denotes for success/truth and false which stands for failure/falsehood. A programmer usually uses considers the value of true equal to 1 and value of false equal to 0.
D.Character literal A character literal is created by enclosing a single character inside single quotation marks. For example: 'a', 'm', 'F', '2', '}' etc. Please note that f for literals begins with L, you should store it in wchar_t type of variable as it is a wide character literal. For e.g.
'y', 'n', L'fu', '(', ']'等。
E.String literals String literals are proper strings that are enclosed in double quotes ("...."). A string literal can have anything such as plain characters, escape sequences, and universal characters. We can break a long line into multiple lines using string literals and separate them using whitespaces. Here are some examples of string literals that are identical strings.
“印度很偉大”“印度很偉大”“印度很偉大”
F.Escape sequence this type of literal is used for some special operation or to denote a special character that cannot be typed using keyboard. For example, newline (enter), tab, question mark, etc. Some common escape sequences are \n to add new line; \t to add tab space; \b to add a backspace etc.