4 ms·
In C, the value 0 is equivalent to false and all nonzero values are equivalent to true. It’s a convention throughout the C standard library to return 0 on succe
by chongli 4y ago
In C, the value 0 is equivalent to false and all nonzero values are equivalent to true. It’s a convention throughout the C standard library to return 0 on success and nonzero when some error occurred. The behaviour of the new checked arithmetic library is consistent with that convention.
- Someone 4y ago> It’s a convention throughout the C standard library to return 0 on success and nonzero when some error occurred. If only it were so simple. read and write, for example, return a number less than zero on error and a non-negative number on success, and malloc returns zero on error, and nonzero on success. The general rule for early C seems to be “whatever’s the best way to cram a return value or an error in an int” (probably the correct decision for the time) Also, these new functions return a bool, which, in C23, gets integer-converted to zero for false and one for true (https://en.cppreference.com/w/c/language/bool_constant https://en.cppreference.com/w/c/language/bool_constant. C17 had macros for true and false, with false being zero) and the reverse, converting to bool similarly has zero fro false (https://en.cppreference.com/w/c/language/conversion#Boolean_conversion https://en.cppreference.com/w/c/language/conversion#Boolean_...): “A value of any scalar type (including nullptr_t) (since C23) can be implicitly converted to _Bool. The values that compare equal to an integer constant expression of value zero are converted to 0 (false), all other values are converted to 1 (true).” (https://en.cppreference.com/w/c/language/bool_constant https://en.cppreference.com/w/c/language/bool_constant)
- dahfizz 4y ago_when the return value is an error code_, zero means success and nonzero means failure. Functions like `read`, `recv`, etc etc don't just return an error code. They return an actual value. Functions that only return an error code like `stat`, `connect`, and the proposed ckd_add, return 0 on success and nonzero on error.
- SAI_Peregrinus 4y agoAnd in shell it's convention for programs to return 0 for success and nonzero when an error occurred. The issue is that in shell, the `true` builtin returns `0` and `false` returns `1`, which is the opposite of C's `bool`. And almost every other language's Boolean type.
- gustedt 4y agoUnfortunately there are several error conventions in the C standard. Here, the committee just standardized existing practice, namely the gcc builtins. We just adjusted the call sequence in putting the pointer parameter for the result first.