简体   繁体   中英

GCC -Wconversion warning for 16-bit addition

What would be the proper way to resolve warnings of this kind in the existing codebase?

void test(uint16_t x, uint16_t y)
{
    // warning: conversion to 'uint16_t' from 'int' may alter its value
    uint16_t value = (x + 1) * y;
    ...
}

All three values are unsigned 16-bit integers and any arithmetical overflows would be performed correctly without warnings it this platform's int was 16-bit, and I don't see another way this piece of code should be written, apart from casting the result due to integer promotion.

  1. Should I cast in all such cases? Casting feels like I am doing something wrong.
  2. Disabling the warning? I would prefer not to disable the warning completely, as it might be useful in some cases.

Should I cast in all such cases? Casting feels like I am doing something wrong.

It's the correct thing to do here, at least if the code should be portable. If it's only ever compiled for 16bit platforms, there shouldn't be a warning, otherwise, silence the warning with an explicit cast to uint16_t :

uint16_t value = (uint16_t) (x + 1) * y;

There's nothing better you can do: all arithmetic operations are carried out as (at least) int and the compiler reminds you of it. Depending on the values of x and y , it's quite possible the result doesn't fit in an uint16_t . Explicitly writing the cast documents you're aware of that and either want the truncation or assure it won't happen.

Note: the following is only true in the 16-bit int case

warning: was about implicit conversion of x to int because 1 is of type int . Later conversion of y to int for same reason would also trigger this.

Simply mark the 1 as unsigned

void test(uint16_t x, uint16_t y)
{
    uint16_t value = (x + 1u) * y;
    ...
}

No casting required.

This will also work in 16 bit case :

void test(uint16_t x, uint16_t y)
{
    uint16_t value = x * y + y;
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM