Best practice for compute the function return value

前端 未结 5 2286
你的背包
你的背包 2020-11-29 09:57

Often I built functions, in C, that checks some parameters and return an error code.

Which is the best approach to stop the values checking when I found an error?

5条回答
  •  伪装坚强ぢ
    2020-11-29 10:19

    The method I use is goto error_exit.

    You have to consider why a function might fail.

    Reason 1 is illegal arguments, like passing a negative to a square root. So assert fail, the error is caller's.

    Reason 2 is out of memory - that's an inherent problem with functions that scale. You need to shunt the failure up, though normally if a program won't give you a small amount of memory to hold, say, a file path, then it's dead.

    Reason 3 is bad grammar. That's a special case of illegal arguments. If the argument is a double for a square root, caller can reasonably be expected to check for negatives. If the argument is a basic program, caller cannot check for correctness except by effectively writing his own parser. So bad grammar needs to be handled as normal flow control.

    Reason 4 is malfunctioning hardware. Nothing much you can do except shunt the error up, unless you are familiar with the specific device.

    Reason 5 is an internal programming error. By definition there is no correct behaviour because your own code is not correct. But you often need to fudge or throw out degenerate cases in geometry, for example.

    The goto error_exit method is the one I favour, however. It keeps the one point of entry . and of exit principle essentially intact, without introducing artificial nesting for memory allocation errors that are less likely to happen than the computer breaking.

提交回复
热议问题