Why does “noreturn” function return?

前端 未结 9 1603
执念已碎
执念已碎 2020-12-25 10:51

I read this question about noreturn attribute, which is used for functions that don\'t return to the caller.

Then I have made a program in C.

         


        
9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-25 11:02

    The noreturn attribute is a promise that you make to the compiler about your function.

    If you do return from such a function, behavior is undefined, but this doesn't mean a sane compiler will allow you to mess the state of the application completely by removing the ret statement, especially since the compiler will often even be able to deduce that a return is indeed possible.

    However, if you write this:

    noreturn void func(void)
    {
        printf("func\n");
    }
    
    int main(void)
    {
        func();
        some_other_func();
    }
    

    then it's perfectly reasonable for the compiler to remove the some_other_func completely, it if feels like it.

提交回复
热议问题