Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Compiler warning "return discards qualifiers from pointer target type"

I get a compiler "warning: return discards qualifiers from pointer target type" from my function below.

unsigned char* getBeginning(const unsigned char * Packet)
{
                    return Packet+3;
}

I have researched this on SO and other places, and it appears the compiler is complaining that although I take in a const pointer, I am returning a non-const pointer.

What I am trying to accomplish is:

1) I want to let the users know that I will not change any of their data in this function, hence the const.

2) However, later functions will use the pointer returned here to make changes, so I don't want to make my return type const as well.

Is there a better way to do this where I don't get a warning? I'm still learning C.

like image 954
user1762250 Avatar asked Jul 18 '14 17:07

user1762250


1 Answers

C does not have an implicit conversion from const-qualified pointer types to non-const-qualified ones, so you should add an explicit one, i.e. a cast. Then the warning will go away:

unsigned char* getBeginning(const unsigned char * Packet)
{
                    return (unsigned char *)Packet+3;
}

Just beware that this function is then mildly "dangerous" as it can hide the dropping of const qualification. But it's no more dangerous than things like strchr in the standard library which do the same. The behavior is perfectly well-defined as long as you refrain from attempting to modify a const-qualified object via the returned pointer.

like image 160
R.. GitHub STOP HELPING ICE Avatar answered Oct 14 '22 17:10

R.. GitHub STOP HELPING ICE