4

The following code produces a "lvalue required as left operand of assignment"

if( c >= 'A' && c <= 'Z'  || c = " " || c = ",") {

I assume I'm writing this wrong, what is wrong? and how would I write it correctly?

1
  • 2
    The code you have shown cannot produce the diagnostic you are getting, unless c is a macro that expands to a non-lvalue. If c is declared as a plain variable, c = " " should produce "incompatible types in assignment" or something similar. My guess is that in your actual code you're using f() = " " (i.e., a function's return value instead of c). Commented Jun 16, 2010 at 3:09

4 Answers 4

12

You should use single quotes for chars and do double equals for equality (otherwise it changes the value of c)

if( c >= 'A' && c <= 'Z'  || c == ' ' || c == ',') {

Furthermore, you might consider something like this to make your boolean logic more clear:

if( (c >= 'A' && c <= 'Z')  || c == ' ' || c == ',') {

Although your boolean logic structure works equivalently (&& takes precedence over ||), things like this might trip you up in the future.

1
  • 2
    FWIW, I'd use ('A' <= c && c <= 'Z') to make that bit of logic clearly show that 'A' and 'Z' are the 'outer' bounds and have the expression most resemble the math-style 'A' <= c <= 'Z' Commented Jun 16, 2010 at 2:00
4

equality is ==, = is assignment. You want to use ==. Also "" is a char*, single quotes do a character.

Also, adding some parens to your condition would make your code much easier to read. Like so

 ((x == 'c' && y == 'b') || (z == ',') || (z == ' '))
2

= is the assigning operator, not the comparing operator. You are looking for ==.

0

Personally, I prefer the minimalist style:

((x == 'c' && y == 'b') || (z == ',') || (z == ' '))

(  x == 'c'  &&  y == 'b'   ||   z == ','   ||   z == ' '  )

or

(  x == 'c'  &&  y == 'b'  ?  z == ','  :  z == ' '  )

against

( x == 'c' && y == 'b' ? z == ',' : z == ' ')
1
  • !!! the html washine has skipped the dubble space around logical operators !!!! --- and that makes all the visible difference ---
    – bill
    Commented Mar 20, 2015 at 14:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.