Hacker News new | past | comments | ask | show | jobs | submit login

> There is a concrete advantage to using a scheme where 0 is true and all other values are false: error codes. True means the operation succeeded correctly, or false because of insufficient permissions, false because there file doesn't exist, false because of io error, false because of timeout etc. bash uses this scheme.

That works perfectly fine if you write the type as an integer type and define 0 as "no error". You can't call that a C "bool" though.




> You can't call that a C "bool" though.

In hardware, C _Bool is just an scalar integer type (1 byte wide almost everywhere these days).

If you define 0 for false, and true otherwise, you can emit much better machine code for all scalar comparisons. For example, when doing scalar == 0 or scalar != 0 (e.g. in null pointer checks) the result is always the scalar itself. The test is a nop, and with "branch on non-zero" instruction, you can just directly branch.

If you define true to some value, you need to actually test whether the scalar is zero, and give it some other value otherwise. That goes from zero instructions to often two instructions (e.g. if the hardware comparison returns 0xffff and you need to convert that to 1).


> You can't call that a C "bool" though.

Correct. It was not my intent to imply otherwise. Like the person I replied to and I reiterated, that ship has sailed.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: