Question

Why can't I compare the results of the random function?

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main (){

srand(time(NULL));

/*Player 1*/
int P1d1, P1d2, P1total;
P1d1 = 1 + rand() % 6;  //Rolls Player 1's first die; random # between 1-6
P1d2 = 1 + rand() % 6;  //Rolls Player 1's second die; random # between 1-6
P1total = P1d1 + P1d2;  //Takes total of both rolls

/*Player 2*/
int P2d1, P2d2, P2total;
P2d1 = 1 + rand() % 6; //Rolls Player 2's first die; random # between 1-6
P2d2 = 1 + rand() % 6; //Rolls Player 2's second die; random # between 1-6
P2total = P2d1 + P2d2; //Takes total of both rolls

if (P1d1 == P1d2 && P2d1 =! P2d2){ <--- ERROR HERE
    printf("Player 1 wins!\n");
    }
else if (P2d1 == P2d2 && P1d1 =! P1d2) {
    printf("Player 2 wins!\n");
    }
}

I get the error message error: lvalue required as left operand of assignment.

I understand that this means the left-hand side of the assignment has to be a variable, but the left-hand side is a variable (int P1d1). Any suggestions?

Was it helpful?

Solution

You probably need to use == (equality) rather than = (assignment). I see you've changed that in your question.

The cause of the error message is:

P2d1 =! P2d2

The inequality operator is !=, not =!.

The way you're written it, it's an assignment = followed by a unary "not" !. And since = has very low precedence, this:

(P1d1 == P1d2 && P2d1 =! P2d2)

is equivalent to this:

((P1d1 == P1d2 && P2d1) = !P2d2)

and of course (P1d1 == P1d2 && P2d1) is not a valid target for an assignment.

This is one of the more ahem interesting things about programming in C. In some languages, a minor typo is likely to introduce a syntax error, and the compiler's error message is likely to tell you exactly what the problem is. In C, minor typos can easily result in code that's still syntactically correct, but that has some absurd meaning -- or, in your case, that produces an error message that's not very illuminating.

A good approach, if you don't understand what a compiler error message means, is to ignore what it says and just look carefully at the earliest line of code that the compiler complains about.

OTHER TIPS

= is an assignment operator. == is a comparison operator.

Use !=.

if (P1d1 == P1d2 && P2d1 =! P2d2){
printf("Player 1 wins!\n");
}

is the same as

if ((P1d1 == P1d2 && P2d1) = (!(P2d2))){
printf("Player 1 wins!\n");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top