概述
This attribute tells the compiler that the function won't ever return, and this can be used to suppress errors about code paths not being reached. The C library functions abort() and exit() are both declared with this attribute:
extern void exit(int) <strong>__attribute__((noreturn))</strong>; extern void abort(void) <strong>__attribute__((noreturn))</strong>;
Once tagged this way, the compiler can keep track of paths through the code and suppress errors that won't ever happen due to the flow of control never returning after the function call.
In this example, two nearly-identical C source files refer to an "exitnow()" function that never returns, but without the __attribute__ tag, the compiler issues a warning. The compiler is correct here, because it has no way of knowing that control doesn't return.
$ <strong>cat test1.c</strong> extern void exitnow(); int foo(int n) { if ( n > 0 ) { exitnow(); /* <em>control never reaches this point</em> */ } else return 0; } $ <strong>cc -c -Wall test1.c</strong> test1.c: In function `foo': <strong>test1.c:9: warning: this function may return with or without a value</strong>
But when we add __attribute__, the compiler suppresses the spurious warning:
$ <strong>cat test2.c</strong> extern void exitnow() <strong>__attribute__((noreturn))</strong>; int foo(int n) { if ( n > 0 ) exitnow(); else return 0; } $ <strong>cc -c -Wall test2.c</strong> <em>no warnings!</em>
最后
以上就是现实鸭子为你收集整理的__attribute__ noreturn的全部内容,希望文章能够帮你解决__attribute__ noreturn所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复