在我正在处理的 C SDL 项目中,我将 typedef
将 char *
编辑为 str
以提高可读性。
现在当我这样做时:
const str title = SDL_GetWindowTitle(win);
其中SDL_GetWindowTitle
返回一个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,所以它不是 an IDE's fault .
提前致谢!
最佳答案
typedef
不是宏替换,所以在你的情况下
const str
const char *
是不同的类型。前者实际上相当于:
char *const
这是一个 char *
类型的 const
值,因此它指向一个可变字符串。在您的示例中,您无法修改 title
,但您可以通过该指针修改 *title
(如果它实际上指向非 const
内存,这取决于 SDL_GetWindowTitle
的作用)。
您必须为 const char *
添加单独的 typedef
才能解决此问题。
关于c - 为什么 GCC 给我这个 `-Wdiscarded-qualifiers` 警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47247313/