为什么海湾合作委员会给我这个'-Wdiscarded-qualifiers'警告?

joH*_*oH1 2 c gcc typedef const compiler-warnings

在C SDL的项目我的工作,我typedefchar *str了可读性.

现在我做的时候:

const str title = SDL_GetWindowTitle(win);
Run Code Online (Sandbox Code Playgroud)

其中SDL_GetWindowTitle返回const char *,我得到:

warning: return discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
Run Code Online (Sandbox Code Playgroud)

将类型更改为时,将删除警告char *:

const char *title = SDL_GetWindowTitle(win);
Run Code Online (Sandbox Code Playgroud)

typedef只是一个类型的别名,对吧?因此,将变量声明为strchar *应该等效,为什么我会收到警告?或者有什么我错过了......?

我在CLI上使用GCC,所以这不是IDE的错.

Thx提前!

Flo*_*mer 5

typedefs不是宏替换,所以在你的情况下

const str
const char *
Run Code Online (Sandbox Code Playgroud)

是不同的类型.前者实际上相当于:

char *const
Run Code Online (Sandbox Code Playgroud)

这是类型的constchar *,因此它指向可变字符串.在您的示例中,您无法修改title,但您可以*title通过该指针进行修改(如果它实际上指向非const内存,这取决于什么SDL_GetWindowTitle).

你必须添加一个单独typedefconst char *来解决这个问题.