Why does “noreturn” function return?

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

    noreturn is a promise. You're telling the compiler, "It may or may not be obvious, but I know, based on the way I wrote the code, that this function will never return." That way, the compiler can avoid setting up the mechanisms that would allow the function to return properly. Leaving out those mechanisms might allow the compiler to generate more efficient code.

    How can a function not return? One example would be if it called exit() instead.

    But if you promise the compiler that your function won't return, and the compiler doesn't arrange for it to be possible for the function to return properly, and then you go and write a function that does return, what's the compiler supposed to do? It basically has three possibilities:

    1. Be "nice" to you and figure out a way to have the function return properly anyway.
    2. Emit code that, when the function improperly returns, it crashes or behaves in arbitrarily unpredictable ways.
    3. Give you a warning or error message pointing out that you broke your promise.

    The compiler might do 1, 2, 3, or some combination.

    If this sounds like undefined behavior, that's because it is.

    The bottom line, in programming as in real life, is: Don't make promises you can't keep. Someone else might have made decisions based on your promise, and bad things can happen if you then break your promise.

提交回复
热议问题