左值和右值表达式L-Value and R-Value Expressions

引用内存位置的表达式称为“左值”表达式。Expressions that refer to memory locations are called "l-value" expressions. 左值表示存储区域的“locator”值或“left”值,并暗示它可以出现在等号 (=) 的左侧。An l-value represents a storage region's "locator" value, or a "left" value, implying that it can appear on the left of the equal sign (=). 左值通常是标识符。L-values are often identifiers.

引用可修改的位置的表达式称为“可修改的左值”。Expressions referring to modifiable locations are called "modifiable l-values." 可修改的左值不能具有数组类型、不完整的类型或带 const 特性的类型。A modifiable l-value cannot have an array type, an incomplete type, or a type with the const attribute. 对于要成为可修改的左值的结构和联合,它们不得具有带 const 特性的任何成员。For structures and unions to be modifiable l-values, they must not have any members with the const attribute. 标识符的名称表示存储位置,而变量的值是存储在该位置的值。The name of the identifier denotes a storage location, while the value of the variable is the value stored at that location.

如果标识符引用内存位置且如果其类型为算术、结构、联合或指针,则该标识符是可修改的左值。An identifier is a modifiable l-value if it refers to a memory location and if its type is arithmetic, structure, union, or pointer. 例如,如果 ptr 是指向存储区域的指针,则 *ptr 是指定 ptr 所指向的存储区域的可修改的左值。For example, if ptr is a pointer to a storage region, then *ptr is a modifiable l-value that designates the storage region to which ptr points.

以下任一 C 表达式可为左值表达式:Any of the following C expressions can be l-value expressions:

  • 整型、浮点、指针、结构或联合类型的标识符An identifier of integral, floating, pointer, structure, or union type

  • 计算结果不为数组的下标 ([ ]) 表达式A subscript ([ ]) expression that does not evaluate to an array

  • 成员选择表达式(->.A member-selection expression (-> or .)

  • 不引用数组的一元间接寻址 (\) 表达式A unary-indirection (****) expression that does not refer to an array

  • 包含在括号内的左值表达式An l-value expression in parentheses

  • const 对象(不可修改的左值)A const object (a nonmodifiable l-value)

    术语“右值”有时用于描述表达式的值以及将其与左值区分开来。The term "r-value" is sometimes used to describe the value of an expression and to distinguish it from an l-value. 所有左值都是右值,但并不是所有右值都是左值。All l-values are r-values but not all r-values are l-values.

    Microsoft 专用Microsoft Specific

    Microsoft C 包括对 ANSI C 标准的扩展,该扩展允许将左值的转换用作左值,只要对象的大小不通过转换来扩展即可。Microsoft C includes an extension to the ANSI C standard that allows casts of l-values to be used as l-values, as long as the size of the object is not lengthened through the cast. (有关详细信息,请参阅类型强制转换。)下面的示例阐释了此功能:(See Type-Cast Conversions for more information.) The following example illustrates this feature:

char *p ;  
short  i;  
long l;  

(long *) p = &l ;       /* Legal cast   */  
(long) i = l ;          /* Illegal cast */  

Microsoft C 的默认设置是启用 Microsoft 扩展。The default for Microsoft C is that the Microsoft extensions are enabled. 使用 /Za 编译器选项禁用这些扩展。Use the /Za compiler option to disable these extensions.

结束 Microsoft 专用END Microsoft Specific

另请参阅See Also

操作数和表达式Operands and Expressions