【转载】C语言中的undefined behavior/unspecified behavior - 序

时间:2024-05-04 21:36:20

嗷嗷的话:

这都是一些细枝末节的东西,我想不做编译器的话,大部分都很难碰到。研究学习这些只是出于对C语言一种偏执狂。

写出来是为了找到和我一样的偏执狂。

在随后的的文章中,首先我写一写191种undefined behavior。不一定是对的,只是我自己的理解。参考的标准是C99.

undefined behavior简单来说就是,如果你的程序违反了C标准中某些准则,那么具体会发生什么,C标准没有定义,也就说得到任何奇怪的结果,都是有可能的。比如说整数溢出就是一个undefined behavior。
unspecified behavior简单来说就是,C标准提供了多种可选方案,具体选择哪一个并没有定义。比如说,函数计算他参数的顺序是一个unspecified behavior。以任何顺序计算都可以。i = i++ + i++;的值也是一个unspecified behavior。

本系列其他文章传送门:

C语言中的undefined behavior系列(1)-- linkage of identifier

一下摘于C99标准。关于behavior的定义

behavior -- external appearance or action

implementation-defined behavior -- unspecified behavior where each implementation documents how the choice is made  
  EXAMPLE An example of implementation-defined behavior is the propagation of the high-order bitwhen a signed integer is shifted right.


locale-specific behavior -- behavior that depends on local conventions of nationality, culture, and language that each implementation documents

EXAMPLE An example of locale-specific behavior is whether the islower function returns true for characters other than the 26 lowercase Latin letters

undefined behavior -- behavior, upon use of a nonportable or erroneous program construct or of erroneous data,for which this International Standard imposes no requirements

NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictableresults, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

EXAMPLE An example of undefined behavior is the behavior on integer overflow

unspecified behavior  behavior where this International Standard provides two or more possibilities and imposes no further requirements on which is chosen in any instance

EXAMPLE An example of unspecified behavior is the order in which the arguments to a function are evaluated.