geohei geohei - 1 month ago 7
C Question

Function return warning about const attribute

I heavily reduced my real code in order to make it as compact as possible for this posting.

My questions is about the

const
attribute. When I compile this ...

const char tmp[] = "anything";

int main(int argc, char *argv[]) {
/* my code */
return 0;
}

char *somefunction (char *c) {
extern const char tmp[];
/* my code */
return tmp;
}


... I get:


warning: return discards 'const' qualifier from pointer target type [enabled by default]


The code works fine.

The
somefunction
didn't touch the string
tmp
, so why does
return
generate this warning?

If I leave
const
away, the warning disappears.

Answer

When you mark something as const you're telling the compiler you're not going to modify it.

You're taking a const char * and returning it as a char *. That breaks the promise of const that you're giving to tmp. Code that calls this function is free to modify what it returns because it doesn't return a const pointer.

Change somefunction to return a const char *:

const char *somefunction (char *c) {
    ...