1

I wan't to open a file in append mode or erase all it's contents based on $flag

static void do_redirect(int filedes, const char *filename, int flag){
int rc;
int fd;

flag == 1 ? fd = open(filename, O_CREAT|O_RDWR|O_TRUNC, 0644) : 
            fd = open(filename, O_CREAT| O_RDWR, 0644);

}

Why do I get llvalue required as left operand of assignment?

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331

3 Answers3

2

Because of precedence. The expression is parenthesised implicitly

(flag == 1 ? fd = open(filename, O_CREAT|O_RDWR|O_TRUNC, 0644) : fd) = open(filename, O_CREAT| O_RDWR, 0644);

and the value of the conditional expression is not an lvalue.

Write

flag == 1 ? (fd = open(filename, O_CREAT|O_RDWR|O_TRUNC, 0644)) : 
            (fd = open(filename, O_CREAT| O_RDWR, 0644));

or move the conditional expression inside the open call.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
2

It's a question of precedence.

I would suggest you rewrite it as such:

fd = open(filename, O_CREATE | O_RDWR | (flag == 1 ? O_TRUNC : 0), 0644);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Why you are getting lvalue error?

You conditional expression is something like:

flag == 1 ? fp = 1 : fp = 2; 

that is parsed in C like:

(flag == 1 ? fp = 1 : fp) = 2;  

  ^ expression            = value   

and you can't assign a value to an expression that that reason for lvalue error.

The correct answer is given by @Daniel Fischer by adding parenthesis you can rectify your conditional expression(actually overriding precedence).

But interesting this you expression is correct in C++ language!
Read Charles Bailey's answer here: Conditional operator differences between C and C++. You will also find an elaborate answer there why you are getting lvalue error.
(my answer is just a reference to there)

Although @Daniel Fischer and @Joachim Pileborg answer you two tricks you can also achieve same like this:

fd = flag == 1 ? -2 : 3 ;

Yes but this is possible only in your case because you are using fd in both true/false expression

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208