整体促销和运营商+ = [英] Integral promotion and operator+=

查看:78
本文介绍了整体促销和运营商+ =的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要消除gcc -Wconversion警告.例如

I need to eliminate gcc -Wconversion warnings. For example

typedef unsigned short     uint16_t;

uint16_t a = 1;
uint16_t b = 2;
b += a;

给予

warning: conversion to 'uint16_t {aka short unsigned int}' from 'int' may alter its value [-Wconversion]
     b += a;
     ~~^~~~

我可以通过以下方式消除这种情况

I can eliminate this by

uint16_t a = 1;
uint16_t b = 2;
b = static_cast<uint16_t>(b + a);

有什么办法可以保留operator+=并消除警告?谢谢.

Is there any way to keep the operator+= and eliminate the warning? Thank you.

编辑

我使用

gcc test.cpp -Wconversion

gcc test.cpp -Wconversion

我的gcc版本是

gcc.exe(Rev3,由MSYS2项目构建)7.2.0

gcc.exe (Rev3, Built by MSYS2 project) 7.2.0

推荐答案

我需要消除gcc -Wconversion警告.

I need to eliminate gcc -Wconversion warnings.

您没有说为什么,但这实际上是不可能的.

You don't say why but this is actually unlikely.

来自此开关上的GCC Wiki页面:

为什么不通过-Wall或至少通过-Wextra启用Wconversion?

隐式转换在C语言中很常见.这与前端没有数据流(请参阅下一个问题)的事实有关,导致难以避免出现警告,提示代码无法正常工作和有效. Wconversion设计用于特定用途(安全审核,将32位代码移植到64位等),在这种情况下程序员愿意接受并解决无效警告.因此,如果未明确请求,则不应启用它.

Implicit conversions are very common in C. This tied with the fact that there is no data-flow in front-ends (see next question) results in hard to avoid warnings for perfectly working and valid code. Wconversion is designed for a niche of uses (security audits, porting 32 bit code to 64 bit, etc.) where the programmer is willing to accept and workaround invalid warnings. Therefore, it shouldn't be enabled if it is not explicitly requested.

如果您不想要它,只需将其关闭.

If you don't want it, just turn it off.

错误的解决方案是将代码与不必要的强制转换混合在一起,从而使其更难以阅读和维护.

Mangling your code with unnecessary casts, making it harder to read and maintain, is the wrong solution.

如果您的构建工程师坚持使用此标志,请问他们为什么,然后请他们停止.

If your build engineers are insisting on this flag, ask them why, and ask them to stop.

这篇关于整体促销和运营商+ =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆