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
  • 267,707
  • 33
  • 569
  • 680
Octavian Marian
  • 65
  • 3
  • 11

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
  • 714,442
  • 84
  • 1,110
  • 1,523
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
  • 88,405
  • 25
  • 200
  • 352
0

You have to use:

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