gpt4 book ai didi

c - 常量表达式和不可修改的左值之间有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 15:50:02 25 4
gpt4 key购买 nike

简而言之,来自 C:

Constant expressions

The compiler recognizes constant expressions in source codeand replaces them with their values. The resulting constant valuemust be representable in the expression’s type. You may use a constantexpression wherever a simple constant is permitted.

Operators inconstant expressions are subject to the same rules as in otherexpressions. Because constant expressions are evaluated at translationtime, though, they cannot contain function calls or operations thatmodify variables, such as assignments.

  1. 什么是常量表达式?它没有定义常量表达式

  2. 常量表达式和不可修改的左值之间有什么区别(例如,数组名称、用 const 声明的左值)

  3. 常量表达式总是非左值吗?

  4. 不可修改的左值是常量表达式吗?

最佳答案

What are constant expressions?

§6.6-常量表达式:

A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be.

对常量表达式的约束之一是

Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not evaluated115).


What are the differences between constant expressions and nonmodifiable lvalues?

不可修改的左值不是常量表达式。 不可修改的值是不能用于修改对象的左值

int const i = 5;

i 指的是一个 const 对象,但它是一个左值,一种称为不可修改左值的特殊左值。

无论在标准中提到“左值”的地方,它实际上都意味着“可修改的左值”(您不会在标准中找到它,但为了清楚起见)

现在让我再解释一下。

int x = 5;
int const *p;

x 是一个非 const 对象,它是一个可修改的左值。 p 是指向 const int 对象的指针。

p = &x;  // This will raise a warning though and hazardous to do.

上面的赋值使用限定转换将 pointer to int 类型的值转换为 pointer to const int.
*px 是指代同一对象的两个不同表达式。可以使用 x

修改此对象
--x;  

但这不能使用 *p 来完成,因为它是不可修改的左值。

--(*p); // Error

常量表达式和不可修改的左值之间的另一个区别是

int const x = 5;
int *p;
/* Assigning address of a non-modifiable object */
p = &x // Correct
/* Assigning address of a constant expression */
p = &5 // Wrong

Are constant expressions always non-lvalues?

是的,常量表达式总是非左值,即右值。

Are nonmodifiable lvalues constant expressions?

关于c - 常量表达式和不可修改的左值之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45677712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com