c - 为什么 C 允许从 const 隐式转换为非常量指针
问题描述
以下代码:
const char * p;
char * i = p;
不能在 CPP 中编译。
错误:从 'const char*' 到 'char* 的无效转换
但是,编译为 C 代码时不会出现编译错误。 为什么 C 允许将 const 指针隐式转换为非 const 指针?
解决方案
C 有一个未定义行为的概念。即使编译器注意到 UB 的可能性,它也允许它编译程序。在许多情况下,警告会被忽略。
在这种情况下(gcc)
warning: initialization discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
推荐阅读
- azure - 如何计算 cosmos DB 中的不同值
- netty - netty 通道和线程和 eventLoop
- selenium-webdriver - 无法实例化类 TestRunner:将 Cucumber 与 TestNG 一起用于 Selenium 代码
- php - 将MongoDB中文档的子数组显示为php中的表
- android - 运行时权限在真实设备上不起作用
- c - 为什么我偶尔会得到不同的结果?【C语言】
- rest - 具有两条路径的 cookie 的 API 设计
- r - 如何在安装之前或之后修改 R 库源代码的特定脚本?
- google-apps-script - 谷歌脚本同一行中的多个条件和前一行中的值的验证
- java - 如何使用事务 java 引发错误