Search code examples
c++arraysvariable-assignmentternary-operatorlvalue

Double scripted array as an lvalue


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


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