(c) expression must be a modifiable lvalue

2019-09-03 02:55发布

if (operation = '+' || operation = '-' || operation = '*' || operation = '/' || operation = '%')//error line
    {
        printf("Enter the first operand:\t\t");
        getchar();
        scanf("%d", &num1);
        printf("Enter the second operand:\t\t");
        getchar();
        scanf("%d", &num2);
}

It gives out an error saying :

Error: expresion must be a modifiable value

It gives me the error on that if line , on all of the arguments but the one that says

operation = '%'

what is the problem ?? thank you guys :)

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-03 03:06

You made a typo and instead of the comparison operator == you wrote the assignment operator =

Instead of

if (operation = '+' || operation = '-' || operation = '*' || operation = '/' || operation = '%')

there must be

if (operation == '+' || operation == '-' || operation == '*' || operation == '/' || operation == '%')

You could write the if statement simpler. For example

const char *Operations = "+-*/%";

char *p = strchr( Operations, operation );

if ( p !=  NULL )
{
        printf("Enter the first operand:\t\t");
        getchar();
        scanf("%d", &num1);
        printf("Enter the second operand:\t\t");
        getchar();
        scanf("%d", &num2);
}

Or even without declaring pointer p

const char *Operations = "+-*/%";

if ( strchr( Operations, operation ) !=  NULL )
{
        printf("Enter the first operand:\t\t");
        getchar();
        scanf("%d", &num1);
        printf("Enter the second operand:\t\t");
        getchar();
        scanf("%d", &num2);
}
查看更多
Lonely孤独者°
3楼-- · 2019-09-03 03:14

You need to use double equal (==) signs, rather than single equals (=):

if (operation == '+' || operation == '-' || operation == '*' //...

the equals (=) is reserved just for assignment, so won't work when you are trying to compare values.

查看更多
甜甜的少女心
4楼-- · 2019-09-03 03:31

As already stated, you must use the equal operator (==) and not the assignment operator (=). What's happening is the following: The compiler tries to make an assignment that looks like

var = (x || y) = var

So it tries to assign the value of var to a boolean expression (namely (x || y)), and this irritates the compiler. This is why it works on the last assignment (%), because then the compiler knows what to do: assign '%' to operation. Still this won't work as you intended, but at least it compiles. You actually can put an assignment in an if statement. What happens is that the value of the assigned variable (i.e. operation) will be evaluated, and the statement is true if the value is != 0, false otherwise.

查看更多
登录 后发表回答