lvalue required as left operand of assignment error when using C++

前端 未结 5 596
耶瑟儿~
耶瑟儿~ 2020-12-28 23:59
int main()
{

   int x[3]={4,5,6};
   int *p=x;
   p +1=p;/*compiler shows error saying 
            lvalue required as left 
             operand of assignment*/
           


        
相关标签:
5条回答
  • 2020-12-29 00:39

    if you use an assignment operator but use it in wrong way or in wrong place, then you'll get this types of errors!

    suppose if you type:
    p+1=p; you will get the error!!

    you will get the same error for this:
    if(ch>='a' && ch='z')
    as you see can see that I i tried to assign in if() statement!!!
    how silly I am!!! right??
    ha ha
    actually i forgot to give less then(<) sign
    if(ch>='a' && ch<='z')
    and got the error!!

    0 讨论(0)
  • 2020-12-29 00:44

    It is just a typo(I guess)-

    p+=1;
    

    instead of p +1=p; is required .

    As name suggest lvalue expression should be left-hand operand of the assignment operator.

    0 讨论(0)
  • 2020-12-29 00:51

    To assign, you should use p=p+1; instead of p+1=p;

    int main()
    {
    
       int x[3]={4,5,6};
       int *p=x;
       p=p+1; /*You just needed to switch the terms around*/
       cout<<p<<endl;
       getch();
    }
    
    0 讨论(0)
  • 2020-12-29 00:56

    Put simply, an lvalue is something that can appear on the left-hand side of an assignment, typically a variable or array element.

    So if you define int *p, then p is an lvalue. p+1, which is a valid expression, is not an lvalue.

    If you're trying to add 1 to p, the correct syntax is:

    p = p + 1;
    
    0 讨论(0)
  • 2020-12-29 00:58

    When you have an assignment operator in a statement, the LHS of the operator must be something the language calls an lvalue. If the LHS of the operator does not evaluate to an lvalue, the value from the RHS cannot be assigned to the LHS.

    You cannot use:

    10 = 20;
    

    since 10 does not evaluate to an lvalue.

    You can use:

    int i;
    i = 20;
    

    since i does evaluate to an lvalue.

    You cannot use:

    int i;
    i + 1 = 20;
    

    since i + 1 does not evaluate to an lvalue.

    In your case, p + 1 does not evaluate to an lavalue. Hence, you cannot use

    p + 1 = p;
    
    0 讨论(0)
提交回复
热议问题