为什么 GCC 会给我这个“-Wdiscarded-qualifiers”警告?
why does GCC give me this `-Wdiscarded-qualifiers` warning?
在我正在处理的 C SDL 项目中,我 typedef
将 char *
编辑为 str
以提高可读性。
现在当我这样做时:
const str title = SDL_GetWindowTitle(win);
其中 SDL_GetWindowTitle
returns a const char *
,我得到:
warning: return discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
当我将类型更改为 char *
:
时警告被删除
const char *title = SDL_GetWindowTitle(win);
typedef 只是类型的别名,对吧?因此,将变量声明为 str
或 char *
应该是等效的,为什么我会收到该警告?还是我错过了什么...?
我在 CLI 上使用 GCC,所以它不是 。
提前致谢!
typedef
s 不是宏替换,所以在你的情况下
const str
const char *
是不同的类型。前者其实相当于:
char *const
这是一个 char *
类型的 const
值,所以它指向一个 mutable 字符串。在您的示例中,您不能修改 title
,但可以通过该指针修改 *title
(如果它实际上指向非 const
内存,这取决于 SDL_GetWindowTitle
的作用).
您必须为 const char *
添加单独的 typedef
才能解决此问题。
在我正在处理的 C SDL 项目中,我 typedef
将 char *
编辑为 str
以提高可读性。
现在当我这样做时:
const str title = SDL_GetWindowTitle(win);
其中 SDL_GetWindowTitle
returns a const char *
,我得到:
warning: return discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
当我将类型更改为 char *
:
const char *title = SDL_GetWindowTitle(win);
typedef 只是类型的别名,对吧?因此,将变量声明为 str
或 char *
应该是等效的,为什么我会收到该警告?还是我错过了什么...?
我在 CLI 上使用 GCC,所以它不是
提前致谢!
typedef
s 不是宏替换,所以在你的情况下
const str
const char *
是不同的类型。前者其实相当于:
char *const
这是一个 char *
类型的 const
值,所以它指向一个 mutable 字符串。在您的示例中,您不能修改 title
,但可以通过该指针修改 *title
(如果它实际上指向非 const
内存,这取决于 SDL_GetWindowTitle
的作用).
您必须为 const char *
添加单独的 typedef
才能解决此问题。