__builtin_trap: when to use it?

…衆ロ難τιáo~ 提交于 2019-12-03 22:56:00

Because exit(1) causes the program to terminate normally with an error status code. See the cppreference page. In contrast __builtin_trap causes the program to terminate abnormally.

The simplest way to see the differences is to look at the guarantees made by exit, if doing one of those things is something you don't want to happen, __builtin_trap would be better.

Debugging is the most common example, as __builtin_trap could trigger a debugger to dump the process, while exit would not (since the program terminates "normally" with an error).

The __builtin functions are not necessarily for optimisation - they are for "doing things that the compiler can't do directly from source code", including support for "special instructions" and "architecture-specific operations". One of the main purposes of __builtin functions is that the compiler will "know" what these do at a later stage. Although there are "library optimisations" in the compiler, the compiler can use __builtin functions much more freely to determine that the behaviour is something specific - for example, __builtin_trap can be relied upon to "not continue to the next instruction", so the compiler doesn't have to worry about code like:

if (x <= 0.0) __builtin_trap();
y = ln(x);

It can then make use of the "fast inline version of ln", since the error has been caught already.

Note also that __builtin_trap is almost guaranteed to end up as a "stop" in the debugger, where exit(1) or some such will just exit the program with a "not success" result code, which is rather annoying if you are trying to figure out where that math error message came from...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!