C 中后缀和前缀之间括号的优先级

发布于 2024-11-25 18:54:52 字数 534 浏览 1 评论 0原文

C 运算符首选项表 指出 () 具有更高的优先级。

代码:

# include <stdio.h>
int main()
{
    int temp=2;
    (temp += 23)++;    //Statement 1
    ++(temp += 23);    //Statement 2
    printf("%d",temp);
    return 0;
}

我的问题是,虽然语句 2 中括号的优先级高于前缀运算符,但为什么会出现错误。 在语句 1 中,两者具有相同的优先级,但求值顺序是从左到右。还是同样的错误。 第三个问题:运算符 += 的优先级低得多,那么为什么它会导致错误。

error: lvalue required as increment operand

The C Operator Preference Table notes the higher precedence of ().

Code:

# include <stdio.h>
int main()
{
    int temp=2;
    (temp += 23)++;    //Statement 1
    ++(temp += 23);    //Statement 2
    printf("%d",temp);
    return 0;
}

My question is while parentheses has higher precedence than pre-fix operator in Statement 2 why there's an error.
In Statement 1 both has same precedence but order of evaluation is from left to right. Still the same error.
Third doubt: operator += has much lower precedence, then why it's causing error.

error: lvalue required as increment operand

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌无敌 2024-12-02 18:54:52

lvalue 是可以分配其他值的值(因为它位于赋值运算符的左侧)。 (temp += 23) 是一个右值。不能为其分配任何内容。

An lvalue is a value that some other value can be assigned to (because it is on the left side of the assignment operator). (temp += 23) is a rvalue. Nothing can be assigned to it.

枉心 2024-12-02 18:54:52

我想补充的一点是,您似乎正在尝试在表达式中多次修改某个值。根据 C99 标准 6.5(2),这是未定义的行为

在上一个和下一个序列点之间,对象应具有其存储的值
通过表达式的求值最多修改一次。此外,先验值
应只读以确定要存储的值。

脚注 71) 显示了示例:

本段呈现未定义的语句表达式,例如

<前><代码>i = ++i + 1;

a[i++] = i;

在允许的情况下

<前><代码>i = i + 1;

a[i] = i;

Something else I'd like to add, is that it looks like you're trying to modify a value more than once in an expression. That's undefined behavior according to C99 standard 6.5(2).

Between the previous and next sequence point an object shall have its stored value
modified at most once by the evaluation of an expression. Furthermore, the prior value
shall be read only to determine the value to be stored.

And footnote 71) shows the example:

This paragraph renders undefined statement expressions such as

i = ++i + 1;

a[i++] = i;

while allowing

i = i + 1;

a[i] = i;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文