4 ms·
In a language like C, NULL solves problems that are otherwise awkward to solve. 1. What should `malloc()` return on failure? 2. How should I indicate that I d
by millstone 8y ago
In a language like C, NULL solves problems that are otherwise awkward to solve.
1. What should `malloc()` return on failure?
2. How should I indicate that I don't care about certain out parameters, e.g. the parameter to `time()`?
3. How should I initialize variables that are going to be used as out parameters, e.g. in `strtol()`?
Other languages address these at the cost of significantly complicating their type system and ABI: generics, multiple return values, etc. In a language intended to be small like C, I'm not sure how you can do better.
- mirimir 8y agoThanks. But ... 1. Why not just return meaningful values? Wouldn't that help in debugging? 2) ??? 3) That makes sense to me.
- AlotOfReading 8y agoC functions can only return one value. Since the stdlib generally adheres to the idea of minimizing overhead, that would mean malloc would have to accept a mutable reference to a reference, so it could assign the reference it returns. Since null references are unusable, using that impossible value as your error flag is a pretty clever optimization.
- mirimir 8y agoThanks, I see that. But isn't ambiguity the tradeoff?
- AstralStorm 8y agoThis point of failure is exactly why exceptions were invented in C++, with low overhead for hot paths. Initialization for out parameters does not matter. In C++ you'd return a tuple or structure or class instead of having multiple return values. It does complicate ABI some.