# lvalue required as left operand of assignment

• 10-29-2012
thames
lvalue required as left operand of assignment
Good evening. Why do I get the error with the ternary operator?

Code:

``` #define FOLD 40 int getLine(char* s, int lim) {   int i;   char c;   for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)     (i % FOLD == 0)? s[i] = '\n' : s[i] = c;     if(c == '\n')     s[i++] = c;     s[i] = '\0';   return i; }```
if I write

Code:

```if(i % FOLD == 0)  s[i] = '\n'; else  s[i] = c;```
I don't get the error. Why?
• 10-29-2012
Nominal Animal
Quote:

Originally Posted by thames
Good evening. Why do I get the error with the ternary operator?
Code:

`    (i % FOLD == 0)? s[i] = '\n' : s[i] = c;`
if I write

Code:

```if(i % FOLD == 0)  s[i] = '\n'; else  s[i] = c;```
I don't get the error. Why?

Because the ternary operator is an operator (that evaluates to a value), not a statement (like if is).

If you want to assign a newline to s[i] when i is a multiple of FOLD, and c otherwise, you can use s[i] = (i % FOLD) ? c : '\n'; or s[i] = (i % FOLD == 0) ? '\n' : c;
Note how the ternary operator is just an expression, not a statement? How it yields the value you assign?

That aside, do you realize that by doing that, you replace every FOLDth character by a newline, causing the replaced character to be lost?

Hint: only increment the index i in the loop definition. If you are at a folding point, append a space to the output array. Otherwise, read a character from input. If the character is EOF or newline, break out of the loop. Otherwise append it to the output array.
• 10-30-2012
thames
Many thanks.