On Undefined Behavior

前端 未结 7 2169
盖世英雄少女心
盖世英雄少女心 2021-01-02 04:14

Generally, UB is regarded as being something that has to be avoided, and the current C standard itself lists quite a few examples in appendix J.

However, there are c

7条回答
  •  死守一世寂寞
    2021-01-02 04:52

    No.

    The compiler take advantage of undefined behavior when optimizing the code. A well-known example is the strict overflow semantics in GCC compiler (search for strict-overflow here) For example, this cycle

    for (int i = 1; i != 0; ++i)
      ...
    

    supposedly relies on your "machine dependent" overflow behavior of signed integer type. However, the GCC compiler under the rules of strict overflow semantics can (and will) assume that incrementing an int variable can only make it larger, and never smaller. This assumption will make GCC optimize-out the arithmetics and generate an endless cycle instead

    for (;;)
      ...
    

    since this is a perfectly valid manifestation of undefined behavior.

    Basically, there's no such thing as "machine-dependent behavior" in C language. All behavior is determined by the implementation and the level of implementation is the lowest level you can ever get to. Implementation isolates you from the raw machine and isolates you perfectly. There's no way to break through that isolation and get to the actual raw machine, unless the implementation explicitly permits you to do so. Signed integer overflow is normally not one of those contexts where you are allowed to access the raw machine.

提交回复
热议问题