1. 4
  1.  

    1. 9

      Rediscover Yoda conditions, you have.

      1. 6

        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.

        1. 3

          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.

          https://web.archive.org/web/20250122195515/https://c-faq.com/null/machnon0.html

          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.

        2. 3

          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.

          1. 5

            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))