Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer parameter was set but never used warning

I have the following function:

void foo(char *ptr_1)
{
    char *ptr_2;

    bar(ptr_2);

    ptr_1 = ptr_2;
}

And get this warning:

parameter "ptr_1" was set but never used

I understand that the warning is technically true, but is irrelevant at the same time. I could suppress it with:

(void)(ptr_1)

But is there a better way?

like image 484
andrey Avatar asked Jan 24 '26 22:01

andrey


2 Answers

It is not an irrelevant warning because the assignment has no effect. You could completely remove ptr_1 from the code without changing its behaviour. Your code is equivalent to this:

void foo(char *)
{
  char *ptr_2;
  bar(ptr_2);
}

In other words, the function parameter isn't used for anything. If your intention was to change the pointer at the caller side, you need to either pass a pointer to a pointer and de-reference it, or return the new value and let the caller use its value:

void foo(char **ptr_1)
{
    char *ptr_2;
    bar(ptr_2);
    *ptr_1 = ptr_2;
}

or

char* foo()
{
    char *ptr_2;
    bar(ptr_2);
    return ptr_2;
}
like image 65
juanchopanza Avatar answered Jan 26 '26 14:01

juanchopanza


I understand that the warning is technically true, but is irrelevant at the same time.

Well, so is the code here. From this point of view of your code, you can get rid of the offending instruction itself.

Also (my personal opinion), it is almost always better to deal with the warnings rather that suppressing them. They are there for a reason ,after all.

like image 23
Sourav Ghosh Avatar answered Jan 26 '26 14:01

Sourav Ghosh