简体   繁体   中英

(invalid lvalue in assignment) this error happens when i run it.what does it mean?

this is the code and the compiler says there is sth wrong with line 7.

include<stdio.h>
main()
{
char m;
 int a,b,n=0;
scanf("%c%d%d",&m,&a,&b);
m=='A' || m=='B' || m=='C' ? n=(3*a)+(5*b) : n=(5*a)+(3*b);
printf("%d\n",n);
}

Use instead

m=='A' || m=='B' || m=='C' ? n=(3*a)+(5*b) : ( n=(5*a)+(3*b));

Otherwise the statement looks like

( m=='A' || m=='B' || m=='C' ? n=(3*a)+(5*b) : n)=(5*a)+(3*b);

Or you could write

n = m=='A' || m=='B' || m=='C' ? (3*a)+(5*b) : (5*a)+(3*b);

The conditional operator in C is defined the following way

conditional-expression:
    logical-OR-expression
    logical-OR-expression ? expression : conditional-expression

As the assignment operator has lower priority then the compiler issues an error because the assignment is excluded from the conditional operator for the third operand

The used by you expression would be valid in C++ because in C++ the operator is defined differently

conditional-expression:
    logical-or-expression
    logical-or-expression ? expression : assignment-expression
                                         ^^^^^^^^^^^^^^^^^^^^^

There is no need to use a complicated statement that confuses everyone, including the compiler. This is just as effective, and a lot easier to read:

if (m=='A' || m=='B' || m=='C')
   n=(3*a)+(5*b);
else
   n=(5*a)+(3*b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM