首页 > 其他 > 详细

__attribute__((noreturn))的用法

时间:2019-07-23 19:52:04      阅读:196      评论:0      收藏:0      [点我收藏+]

 

这个属性告诉编译器函数不会返回,这可以用来抑制关于未达到代码路径的错误。 C库函数abort()和exit()都使用此属性声明:

extern void exit(int)   __attribute__((noreturn));
extern void abort(void) __attribute__((noreturn));

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.

$ cat test1.c
extern void exitnow();

int foo(int n)
{
        if ( n > 0 )
    {
                exitnow();
        /* control never reaches this point */
    }
        else
                return 0;
}

$ cc -c -Wall test1.c
test1.c: In function `foo:
test1.c:9: warning: this function may return with or without a value

 

But when we add __attribute__, the compiler suppresses the spurious warning:

$ cat test2.c
extern void exitnow() __attribute__((noreturn));

int foo(int n)
{
        if ( n > 0 )
                exitnow();
        else
                return 0;
}

$ cc -c -Wall test2.c
no warnings!

 

参考:

https://blog.csdn.net/qq_26093511/article/details/53306323

 

 

__attribute__((noreturn))的用法

原文:https://www.cnblogs.com/sea-stream/p/11233641.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!