Lou
Lou

Reputation: 4474

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.

Upvotes: 0

Views: 275

Answers (2)

Gunther Schulz
Gunther Schulz

Reputation: 625

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;
    ...
}

Upvotes: 3

user2371524
user2371524

Reputation:

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.

Upvotes: 6

Related Questions