Uploaded image for project: 'SonarCFamily'
  1. SonarCFamily
  2. CPP-3394

Proposed rule: result of strcmp should not be treated as boolean

    XMLWordPrintable

    Details

      Description

      Taken from: https://www.teamten.com/lawrence/style/notes.html

      Bad:   if (!strcmp (a, b)) ...
      Good:  if (strcmp (a, b) == 0) ...
      

      Don't use the ! operator on values that are not booleans. The "strcmp" function returns an integer which is less than 0 if a < b, 0 if a == b, and greater than 0 if a > b. (Note: it does not return -1, 0, 1.) The ! operator here is not faster and is misleading because the line reads, "if not string compare" whereas it means "if the strings compare." The same is true about pointers – don't say "if (!ptr)" when "if (ptr == NULL)" is just as fast and much more readable, and same with "if (ptr)" when "if (ptr != NULL)" is better.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              arseniy.zaostrovnykh Arseniy Zaostrovnykh
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: