c++:错误: narrowing conversion of ‘255’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]

编程知识 更新时间:2023-05-02 21:16:28

文章目录

  • 错误
  • 原因
  • 解决

错误

错误的意思,是0xff是一个int 类型,要将int 类型赋给char时,会导变窄转换

uniform.cpp: In function ‘int main():
uniform.cpp:6:29: error: narrowing conversion of ‘255’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]
  char abc[3]={0xff,0xff,0xff};   、、这里列号是29,是最后一个 0xff,也就是所,赋值的时候,是从后往前来的。right to left。
                             ^
uniform.cpp:6:29: error: narrowing conversion of ‘255’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]
uniform.cpp:6:29: error: narrowing conversion of ‘255’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]
为什么会连报3次呢?因为数组就给了三个初值。

原因

在C++11 及以后的版本,这种变换会被默认检查。
-Wno-narrowing (C++ and Objective-C++ only)
For C++11 and later standards, narrowing conversions are diagnosed by default, as required by the standard.
发生在常量的变窄转换,或者从非常量的变窄转换,会打印警告。
A narrowing conversion from a constant produces an error, and a narrowing conversion from a non-constant produces a warning, but ‘-Wno-narrowing’ suppresses the diagnostic. Note that this does not affect the meaning of well-formed code; narrowing conversions are still considered ill-formed in SFINAE contexts.
With ‘-Wnarrowing’ in C++98, warn when a narrowing conversion prohibited by C++11 occurs within ‘{ }’, e.g.
int i = { 2.2 }; // error: narrowing from double to int

解决

unsigned char abc[3]={0xff,0xff,0xff};

更多推荐

c++:错误: narrowing conversion of ‘255’ from ‘int’ to ‘char’ inside { } [-Wnarrowi

本文发布于:2023-04-28 17:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/59e7d727158896d725b7041ec4b4d2ff.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   conversion   narrowing   char   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 109281文章数
  • 27729阅读数
  • 0评论数