geohei geohei - 1 year ago 60
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

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.

didn't touch the string
, so why does
generate this warning?

If I leave
away, the warning disappears.

Answer Source

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) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download