Search code examples
cconstantsdeclarationclionclang-tidy

Const-qualification of parameters in function declaration


I have the following function declaration in a header file:

extern void flash(const char *message, const enum msg_type type);

Basically, it takes two parameters and pushes a corresponding message into a global message queue. Since it doesn't need to modify the parameters, I const-qualified them. However, CLion's static code analyzer emitted a warning about it:

Clang-Tidy: Parameter 'type' is const-qualified in the function declaration; const-qualification of parameters only has an effect on function definitions

enter image description here

Here is my questions:

  1. I const-qualified both parameters, why does only the latter trigger a warning?
  2. Is it really bad? I know it has no effect, but technically specking const qualifiers have no effect too.
  3. Can I get rid of this warning?

Solution

  • The first parameter is of type const char *, or pointer to constant character. This means that you can pass into the function a pointer to a string which you can't modify, for example:

    const char* msg = "Hello, world!";
    flash(msg, SOME_MESSAGE_TYPE);
    

    You can't change the characters in msg; it's a pointer to const char. Passing it to a function with parameter type char* would indicate the function might change them, which would be illegal. This const in the parameter type is relevant to the caller, so is kept.

    On the other hand, enum msg_type is just an enum, and will be copied into the function. When calling the function, I don't care what happens in the body of the function with type; it won't affect anything outside the function. Saying that this is const doesn't make a difference, hence the warning.

    If you change the first parameter to const char *const message, then it'll warn about that too. That would indicate that you can't change what the pointer message points to, which again the caller doesn't care about because whatever pointer it passes in won't change.


    This isn't really bad; it's telling you that you might be confused, but in this case it doesn't hurt anything. You should still get rid of the warning, though, because warnings indicate potential problems and clogging them with non-problematic noise just makes it less likely you'll read the important ones.


    Change the header file, but not wherever flash is implemented, to not have const on the second parameter. Where it's implemented, keep the const so you don't actually change type inside the function body, but it's not needed in the declaration.