Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this undefined behavior in C? (c=x) + (c==y)

I have a bit of sample code that is throwing this warning:

main.c: In function ‘getline_’:
main.c:30:32: warning: operation on ‘c’ may be undefined [-Wsequence-point]

In this particular exercise I was to avoid using the || and && operator, but this doesn't seem like it should produce undefined behavior. The compiler message is just a warning, but I wanted to know for knowings sake. Is this code actually going to produce undefined behavior?

 24 int getline_( char s[], int limit)
 25 {
 26     int i, c;
 27     i=0;
 28     for( i=0; (i<limit-1) + ((c=getchar())!='\n') + (c!=EOF) == 3; i++){
 29            s[i]=c;
 30     }
 31     if( c == '\n' ){
 32         s[i]=c;
 33         i++;
 34     }
 35     s[i]='\0';
 36     return i;
 37 }

It seems to work ok in my basic tests.

Edit: Updated title as per comment, thanks pst.

like image 352
Jeff Welling Avatar asked Dec 13 '22 01:12

Jeff Welling


1 Answers

This is unspecified behavior:

(i<limit-1) + ((c=getchar())!='\n') + (c!=EOF) == 3

the order of evaluation of expressions between sequence points is unspecified in C. It is unspecified if the assignment to c occurs before the equality check with EOF.

In addition to the unspecified behavior, it is also undefined behavior because it violates the sequence points rules and particularly this one:

(C99, 6.5p2) "Furthermore, the prior value shall be read only to determine the value to be stored."

like image 173
ouah Avatar answered Dec 28 '22 10:12

ouah