Why does “noreturn” function return?

前端 未结 9 1605
执念已碎
执念已碎 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:10

    Why function func() return after providing noreturn attribute?

    Because you wrote code that told it to.

    If you don't want your function to return, call exit() or abort() or similar so it doesn't return.

    What else would your function do other than return after it had called printf()?

    The C Standard in 6.7.4 Function specifiers, paragraph 12 specifically includes an example of a noreturn function that can actually return - and labels the behavior as undefined:

    EXAMPLE 2

    _Noreturn void f () {
        abort(); // ok
    }
    _Noreturn void g (int i) {  // causes undefined behavior if i<=0
        if (i > 0) abort();
    }
    

    In short, noreturn is a restriction that you place on your code - it tells the compiler "MY code won't ever return". If you violate that restriction, that's all on you.

提交回复
热议问题