What is a good general approach for deciding return values in C?

后端 未结 8 1694
庸人自扰
庸人自扰 2021-01-17 20:40

My program is written in C for Linux, and has many functions with different patterns for return values:

1) one or two return n on success and -1

8条回答
  •  时光说笑
    2021-01-17 21:23

    So how can I add clarity to my approach when deciding upon return types here?

    Pick one pattern per return type and stick with it, or you'll drive yourself crazy. Model your pattern on the conventions that have long been established for the platform:

    • If you are making lots of system calls, than any integer-returning function should return -1 on failure.

    • If you are not making system calls, you are free to follow the convention of the C control structures that nonzero means success and zero means failure. (I don't know why you dislike bool.)

    • If a function returns a pointer, failure should be indicated by returning NULL.

    • If a function returns a floating-point number, failure should be indicated by returning a NaN.

    • If a function returns a full range of signed and unsigned integers, you probably should not be coding success or failure in the return value.

    Testing of return values is a bane to C programmers. If failure is rare and you can write a central handler, consider using an exception macro package that can indicate failures using longjmp.

提交回复
热议问题