未定义或未指定的行为?
Undefined or unspecified behaviour?
我正在阅读 this article,他们使用以下示例来解释未定义的行为:
// PROGRAM 1
#include <stdio.h>
int f1() { printf ("Geeks"); return 1;}
int f2() { printf ("forGeeks"); return 1;}
int main()
{
int p = f1() + f2();
return 0;
}
然而,这似乎与子表达式求值的顺序有关,并且根据 C 标准(附件 J.1),它是未指定的行为,而不是未定义的行为:
Unspecified behavior: The order in which subexpressions are evaluated and the order in which side effects
take place, except as specified for the function-call () , &&, || , ? : , and comma
operators (6.5)
由于我对阅读官方规范还很陌生,我想知道我是否误解了示例或文档。我知道这可能看起来很迂腐,但我有兴趣以正确的方式学习这些高级主题。
您在问题中提供的link给出了未定义行为的错误示例。 f1
和 f2
在 f1() + f2()
中的评估将是未指定的。请注意,标准说明了 副作用 以及 评估顺序
The order in which subexpressions are evaluated and the order in which side effects take place [...]
f1
和 f2
计算中的副作用(输出到标准输出)不相关,它们不会导致任何未定义的行为。
这与下面的示例没有什么不同
int a = 1;
int b = 1, c;
c = a + b;
表达式 a + b
中未指定 a
和 b
的计算顺序。
我正在阅读 this article,他们使用以下示例来解释未定义的行为:
// PROGRAM 1
#include <stdio.h>
int f1() { printf ("Geeks"); return 1;}
int f2() { printf ("forGeeks"); return 1;}
int main()
{
int p = f1() + f2();
return 0;
}
然而,这似乎与子表达式求值的顺序有关,并且根据 C 标准(附件 J.1),它是未指定的行为,而不是未定义的行为:
Unspecified behavior: The order in which subexpressions are evaluated and the order in which side effects take place, except as specified for the function-call () , &&, || , ? : , and comma operators (6.5)
由于我对阅读官方规范还很陌生,我想知道我是否误解了示例或文档。我知道这可能看起来很迂腐,但我有兴趣以正确的方式学习这些高级主题。
您在问题中提供的link给出了未定义行为的错误示例。 f1
和 f2
在 f1() + f2()
中的评估将是未指定的。请注意,标准说明了 副作用 以及 评估顺序
The order in which subexpressions are evaluated and the order in which side effects take place [...]
f1
和 f2
计算中的副作用(输出到标准输出)不相关,它们不会导致任何未定义的行为。
这与下面的示例没有什么不同
int a = 1;
int b = 1, c;
c = a + b;
表达式 a + b
中未指定 a
和 b
的计算顺序。