2

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
andrey
  • 1,515
  • 5
  • 23
  • 39
  • But why are you setting it? The warning was supposed to raise your attention that you probably wanted to do something else. We usually don't include instructions in the code which has no effect to the execution. – vbence Jun 17 '15 at 09:20
  • 2
    The compiler is trying to tell you that the last line of code in your function is meaningless and fills no purpose. How can that warning be irrelevant? – Lundin Jun 17 '15 at 09:20

3 Answers3

7

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;
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Thank you so much. I thought I was going crazy, and immediately saw what I had done when I found this. – Bob Jul 26 '19 at 18:25
1

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I don't like [some warning](http://stackoverflow.com/questions/28985515/is-warning-c4127-conditional-expression-is-constant-ever-helpful). They are bad. – Mohit Jain Jun 17 '15 at 11:33
  • 1
    @MohitJain Agree. Believe it or not, I read that specific question of yours long back and that's why, I used _almost_ in my answer. :-) – Sourav Ghosh Jun 17 '15 at 11:37
1

Simple way is....

int dClock;//variable initiated without used anywhere.
dClock = dClock;//assign variable to itself to suppress not used warning.

worked in keil!