2
votes

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.

2
Because the return type is char*and not const char*. Change char *somefunction (char *c) to const char *somefunction (char *c) - Jabberwocky
Worked ... many thanks! - geohei

2 Answers

2
votes

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) {
    ...
1
votes

As you are returning a pointer you are giving the possibility to "edit" your data to the caller of the function. This is in contradiction with what you have done right before:

extern const char tmp[];

that's the declaration of a pointer to something which should remain constant, namely non editable. The compiler is just warning you about this contradiction.