简体   繁体   English

这是C中未定义的行为吗? (c = x)+(c == y)

[英]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. 编译器的消息只是一个警告,但我想知道knowings缘故。 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. 编辑:根据评论更新标题,谢谢pst。

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 . 在C中未指定序列点之间的表达式的评估顺序。如果在使用EOF进行相等性检查之前发生对c的赋值,则未指定。

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." (C99,6.5p2)“此外,先前的值应该是只读的,以确定要存储的值。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM