Cplusplus 简明教程

C++ Variable Types

变量为我们提供了程序可以操作的命名存储。C++ 中的每个变量都有一个特定的类型,它确定变量内存的大小和布局;可以在该内存中存储的值的范围;可以对变量应用的操作集。

A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific type, which determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

变量的名称可以由字母、数字和下划线字符组成。它必须以字母或下划线开头。大写和小写字母是不同的,因为 C++ 区分大小写:

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive −

C++ 中有以下基本类型的变量,如上一章中所述:

There are following basic types of variable in C++ as explained in last chapter −

Sr.No

Type & Description

1

bool Stores either value true or false.

2

char Typically a single octet (one byte). This is an integer type.

3

int The most natural size of integer for the machine.

4

float A single-precision floating point value.

5

double A double-precision floating point value.

6

void Represents the absence of type.

7

wchar_t A wide character type.

C++ 还允许定义其他各种类型的变量,我们将在后续章节中介绍,例如 Enumeration, Pointer, Array, Reference, Data structures,Classes

C++ also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes.

以下部分将介绍如何定义、声明和使用各种类型的变量。

Following section will cover how to define, declare and use various types of variables.

Variable Definition in C++

变量定义告诉编译器为该变量创建何处以及创建多少存储空间。变量定义指定数据类型,并包含一个或多个该类型变量的列表,如下所示:

A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type, and contains a list of one or more variables of that type as follows −

type variable_list;

此处, type 必须是有效的 C++ 数据类型,包括 char、w_char、int、float、double、bool 或任何用户定义的对象等, variable_list 可能由一个或多个用逗号分隔的标识符名称组成。此处显示了一些有效的声明:

Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −

int    i, j, k;
char   c, ch;
float  f, salary;
double d;

该行 int i, j, k; 同时声明和定义变量 i、j 和 k;它指示编译器创建类型为 int 的名为 i、j 和 k 的变量。

The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int.

可以在声明中初始化变量(分配一个初始值)。初始化程序由等号后跟一个常量表达式组成,如下所示:

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −

type variable_name = value;

一些示例:

Some examples are −

extern int d = 3, f = 5;    // declaration of d and f.
int d = 3, f = 5;           // definition and initializing d and f.
byte z = 22;                // definition and initializes z.
char x = 'x';               // the variable x has the value 'x'.

对于没有初始化程序的定义:静态存储持续时间的变量会隐式初始化为 NULL(所有字节的值为 0);所有其他变量的初始值都是未定义的。

For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.

Variable Declaration in C++

变量声明向编译器保证存在一个具有给定类型和名称的变量,以便编译器在无需变量的详细信息的情况下继续进行进一步的编译。变量声明仅在编译时才有其意义,编译器在程序链接时需要实际的变量定义。

A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable definition at the time of linking of the program.

当您使用多个文件并在其中一个文件中定义了变量时,变量声明很有用,该变量文件在程序链接时可用。您将使用 extern 关键字在任何位置声明变量。尽管您可以在 C++ 程序中多次声明变量,但只能在文件、函数或代码块中定义一次。

A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your C++ program, but it can be defined only once in a file, a function or a block of code.

Example

尝试以下示例,其中变量已在顶部声明,但在主函数中进行了定义 −

Try the following example where a variable has been declared at the top, but it has been defined inside the main function −

#include <iostream>
using namespace std;

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {
   // Variable definition:
   int a, b;
   int c;
   float f;

   // actual initialization
   a = 10;
   b = 20;
   c = a + b;

   cout << c << endl ;

   f = 70.0/3.0;
   cout << f << endl ;

   return 0;
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

30
23.3333

同样的概念适用于函数声明,您可以在声明时提供函数名称,其实际定义可以在任何其他地方给出。例如 −

Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −

// function declaration
int func();
int main() {
   // function call
   int i = func();
}

// function definition
int func() {
   return 0;
}

Lvalues and Rvalues

C++ 中有两种表达式 −

There are two kinds of expressions in C++ −

  1. lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.

  2. rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.

变量是左值,因此可能出现在赋值的左侧。数字字面量是右值,因此不能赋值,不能出现在左侧。以下是有效的语句 −

Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement −

int g = 20;

但以下不是有效的语句,会生成编译时错误 −

But the following is not a valid statement and would generate compile-time error −

10 = 20;