why lvalue required as increment operand error? [duplicate]

青春壹個敷衍的年華 提交于 2019-12-01 12:27:57

问题


Why lvalue required as increment operand Error In a=b+(++c++); ?

Just Wanted to assign 'b+(c+1)' to 'a' and Increment 'C' by 2 at the same time.

I'M A Beginner Just Wanted A Clarification About What "LVALUE ERROR" Actually Is?

main()
{

int a=1,b=5,c=3;

a=b+(++c++);  

printf("a=%d   b= %d   c= %d \n",a,b,c);
}

回答1:


Postfix increment binds tighter than prefix increment so what you would want would be something like:

a = b + (++c)++;

This is not legal C, though, as the the result of prefix increment (like the result of postfix increment in your example) is not an lvalue. This means that it's just a value; it doesn't refer to a particular object like 'c' any more so trying to change it makes no sense. It would have no visible effect as no object would be updated.

Personally I think that doing it in two statements is clearer in any case.

a = b + c + 1;
c += 2;



回答2:


LVALUE means, that there isn't a variable the operation is supposed to be performed on.

C files are basically nothing but text files, which require a particular formatting, so the compiler can understand it.

Writing something like ++Variable++ is complete nonsense for the compiler.

You can basically imagine ++c as:

Var += 1;
return Var;

while c++ is:

int Buf = Var;
Var += 1;
return Buf;

To 'repair' your code:

void main() {
    int a=1,b=5,c=3;
    a = b + (++c);  //Equals 5 + 4
    printf("a=%d   b= %d   c= %d \n",a,b, ++c);  //a = 9, b = 5, c = 5
}

This way, you'll get the result you wanted, without the compiler complaining.

Please remember, that when using ++c or c++ in a combined operation, the order DOES matter. When using ++c, the higher value will be used in the operation, when using c++, it will operate with the old value.

That means:

int a, c = 5;
a = 5 + ++c;  //a = 11

while

int a, c = 5;
a = 5 + c++;  //a = 10

Because in the latter case, c will only be '6' AFTER it is added to 5 and stored in a.



来源:https://stackoverflow.com/questions/12833706/why-lvalue-required-as-increment-operand-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!