1

at this code

(nr % 10) % 2 == 0 ? a[i] = nr % 10 + 1 : a[i] = nr % 10;

I get a lvalue required as left operand of assignment. Can anyone help me with this?

Oliver Charlesworth
  • 260,367
  • 30
  • 546
  • 667
Octavian Marian
  • 55
  • 3
  • 10

3 Answers3

2

The overall problem with this code is that conditional operator is an expression, not a statement. Although you can use assignment expressions as its part, it's better to do the assignment of the whole expression, like this:

a[i] = (nr % 2) == 0 ? nr % 10 + 1 : nr % 10;
//     ^^^^^^^^
// No need to obtain a remainder of division by 10,
// because 2 is a divisor of 10.

Note: You could avoid the conditional altogether with a simple trick:

a[i] = nr % 10 + (1 - (nr % 2));
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
1

Put parentheses around your last assignment to solve this:

(nr % 10) % 2 == 0 ? a[i] = nr % 10 + 1 : (a[i] = nr % 10);

This is because assignment has a lower precedence than the ternary operator so code like a = b ? d : c is parsed as a = (b ? c : d) and not as (a = b) ? c : d. The assignment between ? and : doesn't need to be placed in parentheses as there isn't any syntactic ambiguity.

fuz
  • 82,933
  • 24
  • 182
  • 332
0

You have to use:

a[i] = (nr % 10) % 2 == 0 ? nr % 10 + 1 : nr % 10;
nnn
  • 2,712
  • 12
  • 17