This hurts readability, since it puts the least-important part of the expression first. The most important thing is what we are comparing. Having worked on a codebase that did this, as well as (many) that do it the conventional way, there is no advantage to this. Plus, you can just enable -Wparentheses to catch this.
And second-off, NULL is (void *)0 on any modern platform, so you can just do if (ptr), which is even more readable.
You’re right, but to be a bit more pedantic: NULL is 0 in C because C defines 0 to be another spelling for NULL in pointer contexts. The bitwise representation doesn’t matter.
Whenever a programmer requests a null pointer, either by writing 0 or NULL, it is the compiler’s responsibility to generate whatever bit pattern the machine uses for that null pointer.
If you have clang-tidy available, there’s a lint to prevent assignments in if conditionals. Swapping the operands just looks too uncanny to me and you have to convince everyone to do it.
Both GCC and clang have warnings for the assignment in conditional mistake, and I believe they’re included in -Wextra. There really isn’t any need for this awkwardness.
One exception: I use reversed comparisons when the left side would otherwise be very long and potentially make the comparison hard to spot.
if (5 == function(lots, of, very + long + argument, expressions))
Rediscover Yoda conditions, you have.
This hurts readability, since it puts the least-important part of the expression first. The most important thing is what we are comparing. Having worked on a codebase that did this, as well as (many) that do it the conventional way, there is no advantage to this. Plus, you can just enable
-Wparenthesesto catch this.And second-off,
NULLis(void *)0on any modern platform, so you can just doif (ptr), which is even more readable.You’re right, but to be a bit more pedantic:
NULLis 0 in C because C defines 0 to be another spelling forNULLin pointer contexts. The bitwise representation doesn’t matter.https://web.archive.org/web/20250122195515/https://c-faq.com/null/machnon0.html
If you have
clang-tidyavailable, there’s a lint to prevent assignments inifconditionals. Swapping the operands just looks too uncanny to me and you have to convince everyone to do it.Both GCC and clang have warnings for the assignment in conditional mistake, and I believe they’re included in
-Wextra. There really isn’t any need for this awkwardness.One exception: I use reversed comparisons when the left side would otherwise be very long and potentially make the comparison hard to spot.