Is undefined behavior only an issue if you are deploying on several platforms?

前端 未结 12 947
谎友^
谎友^ 2020-12-24 10:47

Most of the conversations around undefined behavior (UB) talk about how there are some platforms that can do this, or some compilers do that.

What i

12条回答
  •  情话喂你
    2020-12-24 11:14

    What you are referring to is more likely implementation defined and not undefined behavior. The former is when the standard doesn't tell you what will happen but it should work the same if you are using the same compiler and the same platform. An example for this is assuming that an int is 4 bytes long. UB is something more serious. There the standard doesn't say anything. It is possible that for a given compiler and platform it works, but it is also possible that it works only in some of the cases.

    An example is using uninitialized values. If you use an uninitialized bool in an if, you may get true or false, and it may happen that it is always what you want, but the code will break in several surprising ways.

    Another example is dereferencing a null pointer. While it will probably result in a segfault in all cases, but the standard doesn't require the program to even produce the same results every time a program is run.

    In summary, if you are doing something that is implementation defined, then you are safe if you are only developing to one platform and you tested that it works. If you are doing something that is undefined behavior, then you are probably not safe in any case. There may be that it works but nothing guarantees it.

提交回复
热议问题