(c) expression must be a modifiable lvalue

2.4k views Asked by At
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

There are 3 answers

1
Vlad from Moscow On BEST ANSWER

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);
}
0
minseong On

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
Philipp Murry On

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.