首页 > 解决方案 > 为什么 C 允许从 const 隐式转换为非常量指针

问题描述

以下代码:

  const char * p;
  char * i = p;

不能在 CPP 中编译。

错误:从 'const char*' 到 'char* 的无效转换

但是,编译为 C 代码时不会出现编译错误。 为什么 C 允许将 const 指针隐式转换为非 const 指针?

标签: cpointerscastingconstantsimplicit

解决方案


C 有一个未定义行为的概念。即使编译器注意到 UB 的可能性,它也允许它编译程序。在许多情况下,警告会被忽略。

在这种情况下(gcc)

warning: initialization discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]

https://godbolt.org/z/Q8CHgU


推荐阅读