invalid lvalue in assignment

M

mdh

May I ask why this works:

given:
char s[];
char *posbfr = s;
char *endbfr = s + MAXOP;

void(...){
if (posbfr >= endbfr)
printf("......");
else
*posbfr++ = c ;
}


but this is invalid?

(posbfr >= endbfr) ? printf("......") : *posbfr++ = c ;

(with an "invalid lvalue in assignment") error?

or...is this the dumbest question yet? :)

Thank you.
 
I

Ian Collins

mdh said:
May I ask why this works:

given:
char s[];
char *posbfr = s;
char *endbfr = s + MAXOP;

void(...){
if (posbfr >= endbfr)
printf("......");
else
*posbfr++ = c ;
}


but this is invalid?

(posbfr >= endbfr) ? printf("......") : *posbfr++ = c ;
You are assigning c to the result of the conditional expression, so the
above equivalent to

((posbfr >= endbfr) ? printf("......") : *posbfr++) = c ;
 
P

Peter Pichler

mdh said:
May I ask why this works:
but this is invalid?

(posbfr >= endbfr) ? printf("......") : *posbfr++ = c ;

(with an "invalid lvalue in assignment") error?

Assignment is lower priority than ?:. The compiler sees your expression
as (cond ? x : y) = c;

Try explicit parentheses, like this:

(posbfr >= endbfr) ? printf("......") : (*posbfr++ = c) ;
 
M

mdh

Ian Collins wrote:
You are assigning c to the result of the conditional expression, so the
above equivalent to

((posbfr >= endbfr) ? printf("......") : *posbfr++) = c ;



Ian,
I know I am not then understanding this. I thought, given

expr1 ? expr2 : expr3;

then, if expr1 evaluates to true, then expr2 is evaluated, else if
false, expr3.

So, in the above case, is an assignment not regarded as a valid
expression?
..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top