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

I have a little sample code that throws 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 had to avoid using the || and && , but it doesn’t look like it should cause undefined behavior. A compiler message is just a warning, but I wanted to know for the sake of knowledge. Does this code really create 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 } 

In my basic tests everything is working fine.

Edit: updated title as per comment, thanks pst.

+4
source share
1 answer

This is unspecified behavior:

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

the order in which expressions are evaluated between points in a sequence is not specified in C. It is not defined if assignment c occurs before checking equality with EOF .

In addition to unspecified behavior, this is also undefined behavior because it violates the rules of priority points, and especially this:

(C99, 6.5p2) "In addition, the previous value should only be read to determine the value to be stored."

+13
source

All Articles