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.
This is unspecified behavior:
(i<limit-1) + ((c=getchar())!='\n') + (c!=EOF) == 3the order of evaluation of expressions between sequence points is unspecified in C. It is unspecified if the assignment to
coccurs before the equality check withEOF.In addition to the unspecified behavior, it is also undefined behavior because it violates the sequence points rules and particularly this one: