Should useless type qualifiers on return types be used, for clarity?

c, coding-style, constants, static-analysis

Solution

It's usually better for your code to describe as accurately as possible what's going on. You're getting this warning because the `const` in `const int foo();` is basically meaningless. The API only seems clearer if you don't know what the `const` keyword means. Don't overload meaning like that; `static` is bad enough as it is, and there's no reason to add the potential for more confusion.

`const char *` means something different than `const int` does, which is why your tool doesn't complain about it. The former is a pointer to a constant string, meaning any code calling the function returning that type shouldn't try to modify the contents of the string (it might be in ROM for example). In the latter case, the system has no way to enforce that you not make changes to the returned `int`, so the qualifier is meaningless. A closer parallel to the return types would be:

const int foo();
char * const foo2();

which will both cause your static analysis to give the warning - adding a const qualifier to a return value is a meaningless operation. It only makes sense when you have a a reference parameter (or return type), like your `const char *` example.

In fact, I just made a little test program, and GCC even explicitly warns about this problem:

test.c:6: warning: type qualifiers ignored on function return type

So it's not just your static analysis program that's complaining.

Problem

Our static analysis tool complains about a "useless type qualifier on return type" when we have prototypes in header files such as: ``` const int foo(); ``` We defined it this way because the function is returning a constant that will never change, thinking that the API seemed clearer with `const` in place. I feel like this is similar to explicitly initializing global variables to zero for clarity, even though the C standard already states that all globals will be initialized to zero if not explicitly initialized. At the end of the day, it really doesn't matter. (But the static analysis tool doesn't complain about that.) My question is, is there any reason that this could cause a problem? Should we ignore the errors generated by the tool, or should we placate the tool at the possible cost of a less clear and consistent API? (It returns other `const char*` constants that the tool doesn't have a problem with.)

Original source

Related problems