Question

I was wondering, how would i express it in code?

rand() % 2 == 0 ? map[x][y] = 'm' : map[x][y] = 'M';

when I compile that line in g++, it doesn't give an error. However gcc tells me I need an lvalue left of the assignment statement. I thought maybe I should give them an integer

int i = rand() % 2 ? .......

but that also gives me an error. Can someone please help? Thanks

Was it helpful?

Solution

(See here) From the accepted answer in that post, you can see in C it would evaluate as:

((rand() % 2 == 0) ? map[x][y] = 'm' : map[x][y]) = 'M';

And the statement on the left is not a proper L-value. You could rewrite this as:

map[x][y] = rand() % 2 == 0 ? 'm' : 'M';
rand() % 2 == 0 ? (map[x][y] = 'm') : (map[x][y] = 'M'); // This should work in C, but I do not have gcc handy to verify

OTHER TIPS

You need a lvalue to use the expression the way you did. It's used for assignment like:

bool isFull= (candiesEaten>10) ? true : false;

What you wrote is:

 if(rand() % 2 == 0){
     =map[x][y] = 'm';
 }else{
     =map[x][y] = 'M';
 }

I hope you get the point. The more general format would be:

 lvalue= (statement)? val1 : val2;

and it would actually be:

if(statement){
    lvalue= val1;
}
else{
    lvalue= val2;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top