Bug 62029 - Requesting new warning: missing const-qualifier
Summary: Requesting new warning: missing const-qualifier
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: middle-end (show other bugs)
Version: unknown
: P3 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
Keywords: diagnostic
Depends on:
Blocks: new-warning, new_warning
  Show dependency treegraph
Reported: 2014-08-05 23:55 UTC by mi+gcc
Modified: 2021-12-18 11:19 UTC (History)
2 users (show)

See Also:
Known to work:
Known to fail:
Last reconfirmed: 2017-07-22 00:00:00


Note You need to log in before you can comment on or make changes to this bug.
Description mi+gcc 2014-08-05 23:55:55 UTC
To help facilitate "const-poisoning" of the entire body of C (and C++) code out there, I'd like to see a new warning, that would fire, when a pointer to any object in any scope, that could've been marked as "const", is not.

For example:

mylen(char *string)
      if (string == NULL)
         return 0;
         return strlen(string);

example(struct object *o)
      char *text = get_text(o);
      size_t len = mylen(text);

The above code would warn in mylen, because the function's parameter could be made const. As the developer fixes the low-level function to address the warning, the higher level callers of these functions (such as example()) will start warning -- and that will be a beautiful thing...

Some day the warning may even become part of -Wall.
Comment 1 Martin Sebor 2017-07-22 18:24:32 UTC
Confirmed.  This enhancement would be especially useful in C++.  See also pr80711 for a related  request.  It would make sense to consider both of these together.

In C, one caveat/question specific to this request (pointers) is what to do about C functions like strchr:

  void f (char *p)
    char *q = strchr (p, '\0');
    *q = 'x';

or strtol:

  void g (char *p)
    char *q;
    strtol (p, &q, 0);
    *q = '\0';

To avoid false positives on this code the warning would have to handle these cases specially.  That's not difficult to do for functions like strchr that GCC has intrinsic knowledge of but not for others (like strtol).
Comment 2 Eric Gallager 2021-12-18 11:19:15 UTC
Hm, I thought there was another similar bug requesting a -Wsuggest-const, but I can't seem to find it right now... (no, bug 80711 under "See Also" isn't it; I was thinking of a general-purpose const-suggestions request...)