Cprogramming 简明教程
C - Variables
一个 variable 只不过是一个存储区的名称,我们的程序可以对其进行操作。C 中的每个变量都有一个特定的类型,它确定变量内存的大小和布局;可以存储在那部分内的值的范围;以及可以应用于变量的一组操作。
A variable is nothing but a name given to a storage area 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.
Why Do We Use Variables in C?
C 中的变量是对计算机内存中特定位置的用户分配的名称,它是一组大量随机可访问位置的集合,可以容纳单个位。内存中的每个位置都由二进制(或为了方便而采用十六进制)格式表示的唯一地址标识。
A variable in C is a user-assigned name to a certain location in the computer’s memory, which is a collection of a large number of randomly accessible locations capable of holding a single bit. Each location in the memory is identified by a unique address, expressed in binary (or Hexa-decimal for convenience) format.
由于通过以二进制形式引用其位置来存储和处理内存中的数据非常麻烦,因此像 C 这样的高级语言允许使用用户定义的名称或变量来识别位置。
Since it is extremely cumbersome to store and process the data in the memory by referring to their locations in binary form, high-level languages such as C let the locations be identified by user-defined names or variables.
您可以找到一个合适的助记符标识符并为其分配一个值,而不是识别一个可用内存位置并为其分配一个值。C 编译器将选择一个适当的位置,并将它绑定到您指定的标识符。
Instead of identifying a free memory location and assigning it a value, you can find a suitable mnemonic identifier and assign it a value. The C compiler will choose an appropriate location and bind it to the identifier specified by you.
Naming Conventions of C Variables
变量的名称必须以字母(大写或小写)或下划线 (_) 开头。它可以由字母(大写或小写)、数字和下划线字符组成。C 中变量的名称中不能包含其他字符。
The name of the variable must start with an alphabet (upper or lowercase) or an underscore (_). It may consist of alphabets (upper or lowercase), digits, and underscore characters. No other characters can be a part of the name of a variable in C.
C 中的变量名称区分大小写。例如,“age”与“AGE”不同。
Variable names in C are case-sensitive. For example, "age" is not the same as "AGE".
ANSI 标准识别一个变量名称的长度为 31 个字符。虽然可以选择具有更多字符的名称,但只能识别前 31 个字符。为变量使用反映其打算存储的值的描述性名称被认为是一个好习惯。避免使用可能让你感到困惑的非常短的变量名称。
The ANSI standard recognizes a length of 31 characters for a variable name. Although you can choose a name with more characters, only the first 31 will be recognized. Using a descriptive name for a variable, that reflects the value it intends to store is considered to be a good practice. Avoid using very short variable names that might confuse you.
C 是一种静态类型语言。因此,必须在声明中提到变量的数据类型,在变量名称之前。可以在函数(局部变量)或全局变量中声明变量。可以在单个语句中声明多个相同类型变量。
C is a statically typed language. Hence, the data type of the variable must be mentioned in the declaration before its name. A variable may be declared inside a function (local variable) or globally. More than one variable of the same type may be declared in a single statement.
Example
基于以上规则和约定,这里有一些有效的和无效的变量名称:
Based on the above set of rules and conventions, here are some valid and invalid variable names:
int _num = 5; // valid integer variable
float marks = 55.50; // valid float variable
char choice = '0'; // valid char variable
// invalid variable name
// cannot use "-"
int sub-1 = 35;
//invalid; must have data type
avg = 50;
// invalid; name can be used for
// declaration only once in a function
int choice = 0;
// Valid integer name
int sal_of_employee = 20000;
// Valid because all are of same type
int phy, che, maths;
// error because variables of
// different types in same statement
int sal, float tax;
在 C 中, variables 能够存储属于它识别到的任何类型的变量。因此,变量类型数与 data types in C 数一样多。
In C, variables can store data belonging to any of the types it recognizes. Hence there are as many number of types of variables as the number of data types in C.
Sr.No |
Type & Description |
1 |
char Typically a single octet(one byte). It is an integer type. |
2 |
int The most natural size of integer for the machine. |
3 |
float A single-precision floating point value. |
4 |
double A double-precision floating point value. |
5 |
void Represents the absence of type. |
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; and variable_list may consist of one or more identifier names separated by commas.
一些有效的变量声明显示如下 −
Some valid variable 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; declares and defines the variables i, j, and k; which instruct 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;
Example: Variable Definition and Initialization
看看以下示例:
Take a look at the following examples:
// declaration of d and f
extern int d = 3, f = 5;
// definition and initializing d and f
int d = 3, f = 5;
// definition and initializes z
byte z = 22;
// the variable x has the value 'x'
char x = '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 are undefined.
Variable Declaration in C
根据 ANSI C 标准,所有变量都必须在开头声明。不允许在第一个处理语句之后再声明变量。虽然 C99 和 C11 标准版本已删除这个规定,但它仍然被认为是一种良好的编程实践。可以声明一个变量以便稍后在代码中给它分配一个值,或者可以在声明时对其进行初始化。
As per the ANSI C standard, all the variables must be declared in the beginning. Variable declaration after the first processing statement is not allowed. Although the C99 and C11 standard revisions have removed this stipulation, it is still considered a good programming practice. You can declare a variable to be assigned a value later in the code, or you can initialize it at the time of declaration.
Example: Variable Declaration
// declaration with initialization
int x = 10;
// declare first and assign later
int y;
y = 20;
// define and initialize two variables
int d = 3, f = 5;
// the variable x has the value 'x'
char x = 'x';
一旦声明了某个类型的变量,就不能为其分配任何其他类型的变量。在这种情况下, C compiler 报告类型不匹配错误。
Once a variable of a certain type is declared, it cannot be assigned a value of any other type. In such a case the C compiler reports a type mismatch error.
变量声明向编译器保证存在具有给定类型和名称的变量,以便编译器可以在不需要变量的完整详细信息的情况下继续进行进一步的编译。变量定义仅在编译时才有其含义,编译器在链接程序时需要实际的变量定义。
A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed with further compilation without requiring complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking 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 the program. You will use the keyword "extern" to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.
Example
尝试以下示例,其中变量已在顶部声明,但在主函数中对其进行了定义和初始化 −
Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function −
#include <stdio.h>
// 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;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
在上述代码编译并执行后,将生成以下结果:
When the above code is compiled and executed, it produces the following result:
value of c : 30
value of f : 23.333334
同一个概念适用于函数声明,你在声明函数时提供一个函数名,它可以在其他任何地方给出实际定义。例如 −
The 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 in C
C 中有两种表达式:
There are two kinds of expressions in C:
-
lvalue expressions
-
rvalue expressions
Lvalue Expressions in C
引用存储器位置的表达式称为“左值”表达式。左值可能会显示在赋值的左边或右边。
Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment.
C 中的变量是左值,因此可能会显示在赋值的左边。
Variables in C are lvalues and so they may appear on the left-hand side of an assignment.
Rvalue Expressions in C
“右值”一词指的是存储在存储器中某个地址处的数字。一个“右值”是一个不能为其赋值的表达式,这意味着一个右值可以显示在赋值的右边,但不能显示在赋值的左边。
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-hand side but not on the left-hand side of an assignment.
数值字面量是右值,因此它们可能未分配,且不可出现在左侧。
Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side.
请查看以下有效和无效的声明:
Take a look at the following valid and invalid statements:
// valid statement
int g = 20;
// invalid statement
// it would generate compile-time error
10 = 20;
Variables in C 可根据以下参数分类:
Variables in C can be classified based on the following parameters:
-
Data types − int, float, char or struct types.
-
Scope − global or local variables.
-
Storage type − automatic, static, register or extern.
稍后在本教程中,我们将了解局部和全局类型以及存储类型。
We shall learn about local and global types and storage types later in this tutorial.