C 中的优先运算符
Priority operators in C
我找到了这篇文章(来源:https://education.cppinstitute.org/),我正在尝试理解第二条指令。
你能回答这两个指令有何区别的问题吗?
c = *p++;
和
c = (*p)++;
我们可以解释一下:第一个赋值就好像执行了下面两条不相交的指令;
c = *p;
p++;
也就是说,将p
指向的字符复制到c
变量中;然后,p
增加并指向数组的下一个元素。
第二次赋值如下:
c = *p;
string[1]++;
p
指针不变,仍然指向数组的第二个元素,只是这个元素加1。
我不明白的是,当 =
运算符的优先级低于 ++
运算符时,为什么它不递增。
What I don't understand is why it is not incremented when the =
operator has less priority than the ++
operator.
表达式的值
x++
是x递增前的值
所以如果你写
y = x++;
然后变量 y
在递增之前得到 x
的值。
来自 C 标准(6.5.2.4 后缀递增和递减运算符)
2 The result of the postfix ++ operator is the value of the operand.
As a side effect, the value of the operand object is incremented (that
is, the value 1 of the appropriate type is added to it). ... The
value computation of the result is sequenced before the side effect of
updating the stored value of the operand. ...
如果不是表达式
c = (*p)++;
你会写
c = ++(*p);
然后你得到你期望的结果。这演示了后缀增量运算符 ++ 和前缀(一元)增量运算符 ++ 之间的区别。
当++跟在变量后面时,变量用完后自增。
所以当你有
y = x++;
x在y得到x的值后递增。
这也是 -- 运算符的工作方式。
关于本声明的表述
c = (*p)++;
,你说
What i dont understand is why [p
] is not incremented when the =
operator has less priority than the ++ operator.
有一个非常简单的解释:p
不会作为计算该表达式的结果递增,因为它不是 ++
运算符的操作数。
这部分是因为 =
运算符的优先级较低:因为 =
的优先级很低,所以 ++
的操作数是表达式 (*p)
而不是表达式 c = (*p)
。请特别注意 p
本身在 运行 中甚至不可能成为这种情况下的操作数,这与没有括号的变体不同。
继续,表达式 (*p)
指定 p
指向的事物,就像 *p
单独做的那样。上下文暗示当时,这与 string[1]
指定的相同。 那个是递增的,正如文本所说,它在递增之前的值是后缀++
操作的结果。
我找到了这篇文章(来源:https://education.cppinstitute.org/),我正在尝试理解第二条指令。
你能回答这两个指令有何区别的问题吗?
c = *p++;
和
c = (*p)++;
我们可以解释一下:第一个赋值就好像执行了下面两条不相交的指令;
c = *p;
p++;
也就是说,将p
指向的字符复制到c
变量中;然后,p
增加并指向数组的下一个元素。
第二次赋值如下:
c = *p;
string[1]++;
p
指针不变,仍然指向数组的第二个元素,只是这个元素加1。
我不明白的是,当 =
运算符的优先级低于 ++
运算符时,为什么它不递增。
What I don't understand is why it is not incremented when the
=
operator has less priority than the++
operator.
表达式的值
x++
是x递增前的值
所以如果你写
y = x++;
然后变量 y
在递增之前得到 x
的值。
来自 C 标准(6.5.2.4 后缀递增和递减运算符)
2 The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). ... The value computation of the result is sequenced before the side effect of updating the stored value of the operand. ...
如果不是表达式
c = (*p)++;
你会写
c = ++(*p);
然后你得到你期望的结果。这演示了后缀增量运算符 ++ 和前缀(一元)增量运算符 ++ 之间的区别。
当++跟在变量后面时,变量用完后自增。
所以当你有
y = x++;
x在y得到x的值后递增。
这也是 -- 运算符的工作方式。
关于本声明的表述
c = (*p)++;
,你说
What i dont understand is why [
p
] is not incremented when the = operator has less priority than the ++ operator.
有一个非常简单的解释:p
不会作为计算该表达式的结果递增,因为它不是 ++
运算符的操作数。
这部分是因为 =
运算符的优先级较低:因为 =
的优先级很低,所以 ++
的操作数是表达式 (*p)
而不是表达式 c = (*p)
。请特别注意 p
本身在 运行 中甚至不可能成为这种情况下的操作数,这与没有括号的变体不同。
继续,表达式 (*p)
指定 p
指向的事物,就像 *p
单独做的那样。上下文暗示当时,这与 string[1]
指定的相同。 那个是递增的,正如文本所说,它在递增之前的值是后缀++
操作的结果。