gcc provides additional builtin functions "for optimization".
One of them is void __builtin_trap (void)
which essentially is here to abort the program by executing an illegal command.
From the doc:
__builtin_trap function causes the program to exit abnormally. GCC implements this function by using a target-dependent mechanism (such as intentionally executing an illegal instruction) or by calling abort. The mechanism used may vary from release to release so you should not rely on any particular implementation.
Why would you ever use this rather than exit(1)
or abort
? Why did the gcc developers see this as an optimization function?
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).