编程语言
首页 > 编程语言> > c – L值,指针算法

c – L值,指针算法

作者:互联网

参见英文答案 > Why ++i++ gives “L-value required error” in C?                                     5个
我正在寻找一个解释,下面的代码片段中的行L1和L2如何区分w.r.t l-values,即为什么我在L1中得到:C2105错误,但在L2中没有?

*s = 'a';
printf("%c\n", *s );
//printf("%c\n", ++(*s)++ ); //L1 //error C2105: '++' needs l-value
printf("%c\n", (++(*s))++);  //L2
printf("%c\n", (*s) );

注意:当代码编译为.cpp文件时,我得到了上面的结果.现在,在编译为.c文件时,我在L1和L2两行都得到了相同的错误C2105.为什么L2在C中编译而不在C中编译是另一个谜:(.

如果有任何帮助,我使用的是Visual C Express Edition.

解决方法:

编译器将(* s)看作((* s)),因为后增量的优先级高于预增量.在后递增之后,(* s)变为r值并且不能进一步预递增(这里).
是的,它不是UB的情况(至少在C中).
并且还阅读了这个answer.

对于C中的L2没有给出错误,因为
C 11:5.3.2增量和减量说:

The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated). The
operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a completely-defined object type. The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field. If x is not of type bool, the expression ++x is equivalent to x+=1.

C 11:5.2.6增量和减量说:

The value of a postfix ++ expression is the value of its operand. [ Note: the value obtained is a copy of the original value —end note ] The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a complete object type. The value of the operand object is modified by adding 1 to it, unless the object is of type bool, in which case it is set to true. The value computation of the ++ expression is sequenced before the modification of the operand object. With respect to an indeterminately-sequenced function call, the operation of postfix
++ is a single evaluation. [ Note: Therefore, a function call shall not intervene between the lvalue-to-rvalue conversion and the side effect associated with any single postfix ++ operator. —end note ] The result is a
prvalue
. The type of the result is the cv-unqualified version of the type of the operand.

并且在MSDN site还声明:

The operands to postfix increment and postfix decrement operators must be modifiable (not const) l-values of arithmetic or pointer type. The type of the result is the same as that of the postfix-expression, but it is no longer an l-value.

标签:c-3,pointer-arithmetic,c,lvalue
来源: https://codeday.me/bug/20190831/1777022.html