Lint on C code: parameter of function (a pointer) could be const. *But* I am writing to passed pointer

Viewed 201

I'm using Lint for the first time and it's telling me the following:

parameter 'p_h_attr' of function
    'get_dev_info_service_id_attr(ble_attribute_t *)' could be const

For this function:

static void get_dev_info_service_id_attr(ble_attribute_t *p_h_attr)
{
    p_h_attr->p_attr = (void *)ble_char_system_id_value;
    p_h_attr->attr_len = sizeof(ble_char_system_id_value);
}

However, of course, the compiler complains if I make p_h_attr a const because I'm writing into the passed pointer to the structure.

How can I solve this issue?

3 Answers

Lint advises you to make p_h_attr a const pointer, but not a pointer to const. The placement of the const keyword matters. What is expected is:

static void get_dev_info_service_id_attr(ble_attribute_t * const p_h_attr)
    ...

But as others noted in comments, declaring a parameter const for a C function is at least contreversial: there is no gain because it is passed by value. Of course pointers to const is a quite different thing.

I think it means the following

static void get_dev_info_service_id_attr(ble_attribute_t * const p_h_attr)
{
    p_h_attr->p_attr = (void *)ble_char_system_id_value;
    p_h_attr->attr_len = sizeof(ble_char_system_id_value);
}

That is the pointer itself that should be constant not the pointed data. Though there is no great sense to use the qualifier const for the pointer because it is passed by value. That is the parameter is a local variable of the function

Most linters have the option to add exceptions to particular lines where the linters complains but it isn't right to do so. You should check you linter's documentation to find out how to prevent that from taking it as an error.

Usually, such exceptions take the form of specially formatted comments, which instruct the linter to skip the next line, or a certain code block, or a specific linter warning/error in all files (this may not go in a comment but directly to some config file where the linter has the rules saved).

EDIT

I realize, reading more carefully, that the other answers answer your question better. Hope this helps you in the future, though!

Related