3 ms·
> while (x) I never realized how much I hate this style of code until I started using Go. Go only allows Boolean conditions, so you have to do this: > while (
by svnpenn 4y ago
> while (x)
I never realized how much I hate this style of code until I started using Go. Go only allows Boolean conditions, so you have to do this:
> while (x >= 1)
Yeah, it's more code, but it's more readable too.
- robalni 4y agoSpeaking of the while head, after posting this I realized that there is an optimization you can do by moving the bitshift into the while head, like this: while (x >>= 1) This makes gcc compile the code to one instruction less per iteration because it can use the status flags generated by the bitshift to determine whether to jump. Now the loop will only be 3 instructions long and the entire function 8 instructions. https://godbolt.org/z/fna8de367 https://godbolt.org/z/fna8de367
- svnpenn 4y agowhoosh
- adrian_b 4y agoWhich of the 2 versions is more readable is a matter of personal opinion. Many people consider that the most readable programs are those in which nothing is written in a longer more complex form, if it can be written in a shorter simpler form. The implicit conversion of a value of any type to a Boolean value is not something invented by C. This was first used in LISP I (1960), then in many other programming languages.
- jandrewrogers 4y agoThese are not guaranteed to be equivalent expressions even for integer types. It improperly conflates boolean casts (the first case) and boolean comparisons (the second case). In languages like C++ this is an important and commonly used semantic distinction that enables cleaner abstractions because the latter case is making assumptions about the type implementation. Both styles are used but they have distinct meanings in context.