Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boolean expression in C

I found this expression in a C program and I didn't get it :

 struct stack_rec *ss;                                          
 ss=(struct stack_rec *)EMalloc(sizeof(struct stack_rec));       
 if (ss) {                                                      
   int res;                                                     
   res = (ss->elem  = * i , 1); // what does this mean ????
   if (res <= 0)                                                
     return res;                                                
   if (*s == 0) {                                               
     ss->next = 0;                                              
   } else {                                                     
     ss->next = *s;                                             
   }                                                            
   *s = ss;                                                     
   return 2;                                                    
 }                                                              
 return 0;                                                      

What does res = (ss->elem = * i , 1); mean? Is it a boolean expression? I've tried it with a 0 instead of 1 and it always returns the value of the second parameter! Can anyone explain this expression, please?

like image 501
Joy Avatar asked Dec 27 '22 18:12

Joy


2 Answers

Looks broken. It's a use of the comma operator, which simply evaluates to the value of the final expression, i.e. 1.

Therefore, since that code is equivalent to:

ss->elem = *i;
res = 1;

The subsequent testing of res seem pointless, and thus broken.

like image 200
unwind Avatar answered Jan 12 '23 17:01

unwind


The comma u see is a not very much used C operator.

Basically, what it does is execute the 2 statements (ss->elem = *i; and 1;). The statement 1; doesn't realy do much.

After that it returns the result from the last statement (in this case 1)

like image 30
Minion91 Avatar answered Jan 12 '23 16:01

Minion91